rfmoz
rfmoz

Reputation: 1111

How to get all lines after a line number

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

Answers (5)

Daniel Slater
Daniel Slater

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

kev
kev

Reputation: 161604

awk solution:

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

Upvotes: 2

potong
potong

Reputation: 58351

This might work for you:

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

Upvotes: 1

mouviciel
mouviciel

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

SiegeX
SiegeX

Reputation: 140227

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

Upvotes: 5

Related Questions