0

I have a text file which I want to extract after "String1" and before "String2" using unix shell commands such as grep, awk, sed. Part of a text file as follows(I need to get after "Specific" and before the second dashed line):

    ------------------
    Specific:
    line1
    line2
    ------------------
    line3
Ramin
  • 891
  • 2
  • 10
  • 16
  • That was great, just a quick question: how can I extract After and Before. The code presented takes takes the line starting with the pattern – Ramin Jan 08 '14 at 15:57
  • 1
    To make it more clear, what is your expected output? – fedorqui Jan 08 '14 at 16:04

1 Answers1

4

Based on Extract lines between two patterns from a file:

$ awk '/------------------/ {p=0}; p; /Specific/ {p=1}'  file
line1
line2

Quoting my own explanation:

  • When it finds pattern1, then makes variable p=1.
  • it just prints lines when p==1. This is accomplished with the p condition. If it is true, it performs the default awk action, that is, print $0. Otherwise, it does not.
  • When it finds pattern2, then makes variable p=0. As this condition is checked after p condition, it will print the line in which pattern2 appears for the first time.

So the difference is that ------------------ line is checked before printing, so that the flag can be stopped. And Specific line is checked after printing, so that the flag is turned on without printing this specific line.

It could also be done using next after setting p=1 so awk jumps to the next line:

awk '/------------------/ {p=0} /Specific/ {p=1; next} p' file
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598