Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search for last occurrence of the pattern in a file and delete everything after that excluding pattern line

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

2 Answers

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.
  • the 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
like image 129
fedorqui 'SO stop harming' Avatar answered Dec 09 '25 03:12

fedorqui 'SO stop harming'


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
like image 23
Ed Morton Avatar answered Dec 09 '25 03:12

Ed Morton