Discuss Regarding awk start and end pattern in the Linux Help forum on Dev Shed. Regarding awk start and end pattern Linux Help forum discussing topics including usage, troubleshooting, modules, and distributions. Linux is an open source OS, based on UNIX.
Posts: 14
Time spent in forums: 6 h 41 m
Reputation Power: 0
Regarding awk start and end pattern
Hi,
In a file I am trying to find a pattern in this way.
File.txt
Line 1...
Line 2...
...
...
Start Pattern
...
...
XXXXEnd Pattern
pattern line 1...
pattern line 2...
YYYYEnd Pattern
...
...
...
ZZZZEnd Pattern
...
...
EOF
So using `awk '/Start Pattern/,/End Pattern/' File.txt` I can get the following:
XXXXEnd Pattern
pattern line 1...
pattern line 2...
YYYYEnd Pattern
Now I want the End pattern line only. Meaning, in this case YYYYYEnd Pattern and NOT the ZZZEnd Pattern line/s.
I tried `awk '/Start Pattern/,/End Pattern/' File.txt` | awk -F"\n" '{print $4}' or `awk '/Start Pattern/,/End Pattern/' File.txt` | awk -F"\r" '{print $4}'
But I receive nothing. The reason behind, the whole return string is not separated by LF or CR. I am really surprised.
Well, when I tried this
[color=blue]`awk '/Start Pattern/,/End Pattern/' File.txt` | awk -F"\n" '{print $1}'
Output is:
XXXXEnd Pattern
pattern line 1...
pattern line 2...
YYYYEnd Pattern
Which means awk is returning the whole string without \n\r or what?
Need an explanation please.
Posts: 2,108
Time spent in forums: 1 Month 1 Week 1 Day 4 h 41 m
Reputation Power: 1485
Your examples given the file contents shown do not, to my tired eyes, make sense.
Your first awk command outputs 4 lines, that last one of which is the line you want? If so, just pipe that output into a tail -1?
__________________
The moon on the one hand, the dawn on the other:
The moon is my sister, the dawn is my brother.
The moon on my left and the dawn on my right.
My brother, good morning: my sister, good night.
-- Hilaire Belloc
Posts: 14
Time spent in forums: 6 h 41 m
Reputation Power: 0
To process each occurance one by one...
Hi Simon,
Thanks for your reply.
That really helped.
But I forgot to mention one important thing here.
The start/end patterns are repetitive in the file.
So, I want to process this pattern occurrence one by one.
eg.
line1..
line2..
# First pattern
start pattern
...
...
end pattern
....
....
# Second pattern
start pattern
...
...
end pattern
...
...
# Third pattern
start pattern
...
...
end pattern
...
line n...
When I execute `awk '/start pattern/,/end pattern/' file.txt` I get
start pattern
...
...
end pattern
start pattern
...
...
end pattern
start pattern
...
...
end pattern
Now, how can I process each occurrence one by one?
Should work for you ... at awk start, set a flag variable to 0, then when you find a 'start pattern' set it to 1 to indicate it's been found.
Also search for 'end pattern' and if we have already found the start pattern this is the line we want, so print it, and set the flag variable back to 0.