1

How to grep non consecutive patterns...

I run this command.

grep -B 1 -A 2 "field-2-value" inputFile.txt |grep -v "field-3"

which yields these 4 outputs.

  [field-1]xxx[/field-1] 
  [field-2]field-2-value[/field-2] 
  [field-5]true[/field-5] 
  -- 
  [field-1]yyy[/field-1] 
  [field-2]field-2-value[/field-2] 
  [field-4]field-4-value[/field-4] 
  -- 
  [field-1]zzz[/field-1] 
  [field-2]field-2-value[/field-2] 
  [field-5]false[/field-5] 
  -- 
  [field-1]mmm[/field-1] 
  [field-2]field-2-value[/field-2] 
  [field-4]field-4-value[/field-4]

I am only interested in the 2nd and last results that have field-2 and field-4 values:

 
  [field-1]yyy[/field-1]
  [field-2]field-2-value[/field-2]
  [field-4]field-4-value[/field-4]

  [field-1]mmm[/field-1]
  [field-2]field-2-value[/field-2]
  [field-4]field-4-value[/field-4]

The inputFile.txt looks like this:

[RECORD id="1"]
  [field-1]xxx[/field-1]
  [field-2]field-2-value[/field-2]
  [field-3]hello[/field-3]
  [field-5]true[/field-5]
[/RECORD]
[RECORD id="2"]
  [field-1]yyy[/field-1]
  [field-2]field-2-value[/field-2]
  [field-3]hello[/field-3]
  [field-4]field-4-value[/field-4]
[/RECORD]
[RECORD id="3"]
  [field-1]zzz[/field-1]
  [field-2]field-2-value[/field-2]
  [field-3]hello[/field-3]
  [field-5]false[/field-5]
[/RECORD]
[RECORD id="4"]
  [field-1]mmm[/field-1]
  [field-2]field-2-value[/field-2]
  [field-3]hello[/field-3]
  [field-4]field-4-value[/field-4]
[/RECORD]

I am almost tempted to write a shell script to run two sets of operations: First generate a file that has these outputs for each file that contains these results. And then remove block of lines that don't have field-4. Help!

  • Looks like I can accomplish this by grep -B 3 "field-4-value" inputFile.txt | grep -v "field-3" – Joy Kola Aug 11 '17 at 19:01
0
sed -ne '
   /field-2-value/!{h;d;}
   H;n;n;/field-4/!d;H;g;s/$/\n/p
' inputFile.txt

We are rejecting all lines that are not containing /field-2/ but storing them in hold. (Only the last one gets to be saved)

So when we do see /field-2/ line, we append it to hold, skip over next line, then check whether the next-to-next line contains /field-4/. It it doesn't we drop it OTW we append it to hold, then bring over the hold and print it after adding a trailing newline, for the sake of separating out the records printed.


Results:

  [field-1]yyy[/field-1]
  [field-2]field-2-value[/field-2]
  [field-4]field-4-value[/field-4]

  [field-1]mmm[/field-1]
  [field-2]field-2-value[/field-2]
  [field-4]field-4-value[/field-4]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.