2
votes

I have tried this awk command, but for some reason it is not printing out the data between two patterns

This is my entire awk command

for file in `cat out.txt`
do
      awk -v ff="$file" 'BEGIN {print "Start Parsing for"ff} /ff-START/{flag=1; next}/ff-END/{flag=0}flag;  END{print "End Parsing"ff}' data.txt
done

This is the content of data.txt

JOHN SMITH-START
Device,Number
TV,1
Washing Machine,1
Phones, 5
JOHN SMITH-END
MARY JOE-START
Device,Number
TV,3
Washing Machine,1
Phones, 2
MARY JOE-END

and there are 100 more similar lines here the patterns is NAME-START and NAME-END. So for eg JOHN SMITH-START is the first pattern and then JOHN SMITH-END is the second pattern, and I want to extract the data between these two which is

Device,Number
TV,1
Washing Machine,1
Phones, 5

But the output I get is

Start Parsing forJOHN SMITH
End ParsingJOHN SMITH

Content of out.txt is

JOHN SMITH
MARY JOE
1

1 Answers

5
votes

With your shown samples, could you please try following.

awk '/JOHN SMITH-END/ && found{exit} /JOHN SMITH-START/{found=1;next} found' Input_file

Explanation: Adding detailed explanation for above.

awk '                         ##Starting awk program from here.
/JOHN SMITH-END/ && found{    ##Checking condition if line contains JOHN SMITH-END and found is SET then do following.
  exit                        ##exiting from program from here.
}
/JOHN SMITH-START/{           ##Checking condition if line contains JOHN SMITH-START then do following.
  found=1                     ##Setting found to 1 here.
  next                        ##next will skip all further statements from here.
}
found                         ##If found is set then print that line.
' Input_file                  ##Mentioning Input_file name here.

NOTE: In case you want to use variables in awk for search then try following:

awk -v start="JOHN SMITH-START" -v end="JOHN SMITH-END" '$0 ~ end && found{exit} $0 ~ start{found=1;next} found' Input_file