6

I have a file like this:

string log 1 
string log 2
string match
string log 4
string match
string log 5
string log 6

I need to get all the lines after the last string match. How can I do it in bash?

0

5 Answers 5

8

First, find the last string match:

line=$(grep -n 'string match' myFile | cut -d: -f1 | tail -1)

Then, print all lines up to that last string match:

sed -n "1,${line}p" myFile

If you need all lines after last match:

sed -n "$((line+1))"',$p' myFile
5

I'm going to assume in bash allows for some external binary calls. With that in mind:

All lines after the last match

tac infile | sed '/string match/,$d' | tac

Output

$ tac infile | sed '/string match/,$d' | tac
string log 5
string log 6

All lines before the last match

tac infile | sed '1,/string match/d' | tac

Output

$ tac infile | sed '1,/string match/d' | tac
string log 1
string log 2
string match
string log 4
2
  • sorry, I need all lines after the last match
    – rfmoz
    Feb 14, 2012 at 9:38
  • @Rikr np, now you have both ways =)
    – SiegeX
    Feb 14, 2012 at 9:45
2

awk solution:

$ awk 'FNR==NR{if(/match/)x=NR; next}; FNR>x' input.txt{,}
string log 5
string log 6
1

This might work for you:

sed 'H;/string match/,+1h;$!d;x' file
0

I would personally use this sed method:

-bash-4.1$ cat file | sed -n 'H; /string match/h; ${g;p;}'
string match
string log 5
string log 6
-bash-4.1$ cat file | sed -n 'H; /string match/h; ${g;p;}' | grep -v 'string match'
string log 5
string log 6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.