Reputation: 1111
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?
Upvotes: 6
Views: 9443
Reputation: 123
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
Upvotes: 0
Reputation: 161604
awk
solution:$ awk 'FNR==NR{if(/match/)x=NR; next}; FNR>x' input.txt{,}
string log 5
string log 6
Upvotes: 2
Reputation: 67831
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
Upvotes: 8
Reputation: 140227
I'm going to assume in bash allows for some external binary calls. With that in mind:
tac infile | sed '/string match/,$d' | tac
$ tac infile | sed '/string match/,$d' | tac
string log 5
string log 6
tac infile | sed '1,/string match/d' | tac
$ tac infile | sed '1,/string match/d' | tac
string log 1
string log 2
string match
string log 4
Upvotes: 5