How to grep the last occurrence of a line pattern

83,304

Solution 1

I'm not sure if I got your question right, so here are some shots in the dark:

  • Print last occurence of x (regex):

    grep x file | tail -1
    
  • Alternatively:

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

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

    tac file | awk '!flag; /x/{flag = 1};' | tac
    

Solution 2

grep -A 1 x file | tail -n 2

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

or in a reversed way:

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

Note: You should make sure your pattern is "strong" enough so it gets you the right lines. i.e. by enclosing it with ^ at the start and $ at the end.

Solution 3

This might work for you (GNU sed):

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

Saves the last x and what follows in the hold space and prints it out at end-of-file.

Solution 4

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

awk '{a=a"\n"$0; if ($0 == "x"){ a=$0}}  END{print a}' file
Share:
83,304
Admin
Author by

Admin

Updated on May 02, 2021

Comments

  • Admin
    Admin about 3 years

    I have a file with contents

    x
    a
    x
    b
    x
    c
    

    I want to grep the last occurrence,

    x
    c
    

    when I try

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

    it lists all the lines, beginning x to c.