I am trying to search for last occurrence of the pattern in the file and delete everything after the line containing last pattern. I wonder if its possible using awk or sed. thanks in Advance.
aaaaaa bbbbb cccccc
aaaaaa pattern dddddd
eeeeee fffff gggg
qqqq eeee rrrr
desired output:
aaaaaa bbbbb cccccc
aaaaaa pattern dddddd
tac to the rescue:
$ tac b | awk '/pattern/ {p=1}p' | tac
aaaaaa bbbbb cccccc
aaaaaa pattern dddddd
tac does concatenate and print the file in reverse.awk code is explained in my answer to your previous question, delete everything before pattern including pattern using awk or sed.Another example:
$ cat a
aaaaaa bbbbb cccccc
aaaaaa pattern dddddd
eeeeee fffff gggg
aaaaaa pattern dddddd
qqqq eeee rrrr
$ tac a | awk '/pattern/ {p=1}p' | tac
aaaaaa bbbbb cccccc
aaaaaa pattern dddddd
eeeeee fffff gggg
aaaaaa pattern dddddd
awk '
BEGIN { ARGV[ARGC++] = ARGV[ARGC-1] }
NR==FNR { if (/pattern/) lastLine = NR; next }
{ print }
FNR == lastLine { exit }
' file
To demonstrate how postfix works above (see comments below):
$ awk 'BEGIN{ i=3; a[i++] = i; for (j in a) print j, a[j]; print i }'
3 3
4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With