簡體   English   中英

如何刪除與sed模式第二次匹配之前的所有行?

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

我有以下文件:

first
second
third
fourth
third
fifth
sixth

使用cat file | sed -n '/third/,$p' cat file | sed -n '/third/,$p'我可以從第一個匹配開始打印,以獲得:

third
fourth
third
fifth
sixth

是否可以修改sed命令,使其本質上忽略第一個匹配項並從第二個匹配項打印? 那將是:

third
fifth
sixth

這是一個awk ,它通過保留一個緩沖區來存儲一行中出現third行的所有行,並在再次找到third行時重置緩沖區,來完成此操作:

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

third
fifth
sixth

或者,您可以使用以下tac + awk

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

third
fifth
sixth

與sed:

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

輸出:

third
fifth
sixth

與gnu sed

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM