简体   繁体   中英

How to delete all lines before the second match of a pattern with sed?

I have the following file:

first
second
third
fourth
third
fifth
sixth

Using cat file | sed -n '/third/,$p' cat file | sed -n '/third/,$p' I can print starting from the first match, in order to get:

third
fourth
third
fifth
sixth

Is it possible to modify the sed command such that it essentially ignores the first match and prints from the second match? That would be:

third
fifth
sixth

Here is an awk that does that by keeping a buffer to store all lines from occurrence of third in a line and resetting the buffer when third is found again:

awk '/third/{p=$0 RS; next} p{p=p $0 RS} END{printf "%s", p}' file

third
fifth
sixth

Alternatively, you may use this tac + awk :

tac file | awk '1; /third/{exit}' | tac

third
fifth
sixth

With sed:

sed '1,/third/d' file | sed -n '/third/,$p'

Output:

third
fifth
sixth

与gnu sed

sed '/third/!d;:A;N;/\nthird/!{s/[^\n]*\n//;bA };s/[^\n]*\n//;:B;N;bB' infile

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