0

I have multiple blocks of awk that are printed in the following method:

awk '/<TAG>/ {print "Before"} 
     /<TAG>/,/<\/TAG>/ {print} 
     /<\/TAG>/ {print "After"}' ${LOG} > OUTPUT.txt;

AT this stage, there are the same XMLs with different data being outputted. I'd like that Output.txt will contain only the awk blocks that have a specific value within them. If this value appears once or multiple times, print the block.

Example:

Input:

<TAG>
    #1
    <InnerTAG something="50">Value</InnerTAG>
</TAG>
<TAG_Two>
    #2
    <InnerTAG something="60">Value2</InnerTAG>
</TAG_Two>
<TAG>
    #2
    <InnerTAG something="60">Value2</InnerTAG>
</TAG>

Print only the TAG blocks where something="60"

Output.txt:

Before
<TAG>
    #2
    <InnerTAG something="60">Value2</InnerTAG>
</TAG>
After

Currently, my code only prints the TAG blocks, but I'd like to "filter" it down to only the TAG blocks with something="60", or even the inner Value. essentially, by any value within the block.

How would I go about to do this?

Also, if anyone has a more detailed source to read about awk besides the following post, you'll also get an upvote and my appreciation :) Is a /start/,/end/ range expression ever useful in awk?

Cheers!

Community
  • 1
  • 1
Gal Appelbaum
  • 1,905
  • 6
  • 21
  • 33
  • You'll need to accumulate the lines in the block until you see the marker you care about and only then print them (and throw them away when you get to an end marker without having seen it obviously). – Etan Reisner Sep 03 '15 at 14:18

1 Answers1

1

awk to the rescue

awk '/<TAG>/{f=1;c=0} f{d[c++]=$0} /<\/TAG>/{f=0} /60/&&f{for(i in d)print d[i]}'

you may need to specify your pattern match in more detail, here I just used 60 as proof of concept.

karakfa
  • 66,216
  • 7
  • 41
  • 56
  • Hi, Can you explain your answer in a bit more detail? It looks good, I'm going to try it asap, but I'd like to understand it as well :P – Gal Appelbaum Sep 05 '15 at 20:12
  • 1
    With the start tag set a flag and start a counter, accumulate records, with close tag reset the flag. When pattern matches and flag was set (means within tag) print the accumulated rows. – karakfa Sep 05 '15 at 21:35
  • I'll try this out tomorrow at work and hopefully upvote you and mark you as answer too :) thanks for the help! – Gal Appelbaum Sep 05 '15 at 22:29