Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grep the last occurrence of a line pattern

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.

like image 260
user3702858 Avatar asked Jun 03 '14 11:06

user3702858


1 Answers

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 
like image 185
steffen Avatar answered Sep 21 '22 07:09

steffen