How to find the last line pattern

I have a content file

x a x b x c 

I want to see the last case

 x c 

when i try

 sed -n "/x/,/b/p" file 

it lists all lines from x to c .

+12
bash shell grep awk sed
source share
4 answers

I'm not sure if I understood your question correctly, so here are a few shots in the dark:

  • Print the last occurrence of x (regular expression):

     grep x file | tail -1 
  • As an alternative:

     tac file | grep -m1 x 
  • Print the file from the first line to the end:

     awk '/x/{flag = 1}; flag' file 
  • Print the file from the last corresponding line to the end (prints all lines in case of discrepancy):

     tac file | awk '!flag; /x/{flag = 1};' | tac 
+29
source share

This may work for you (GNU sed):

 sed '/x/h;//!H;$!d;x' file 

Saves the last x and what follows on hold, and prints it at the end of the file.

+3
source share

not sure how to do this using sed , but you can try awk

 awk '{a=a"\n"$0; if ($0 == "x"){ a=$0}} END{print a}' file 
+1
source share
 grep -A 1 x file | tail -n 2 

-A 1 tells grep to print one line after the match string
with tail you get the last two lines.

or in reverse order:

 tac fail | grep -B 1 x -m1 | tac 

Note: you must ensure that your pattern is strong enough so that you get the correct lines. that is, enclosing it in ^ at the beginning and $ at the end.

+1
source share

All Articles