简体   繁体   中英

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?

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

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

awk solution:

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

这可能对你有用:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM