簡體   English   中英

您可以使用sed刪除匹配項,之后僅刪除某些行嗎?

[英]Can you use sed to delete match and only certain lines after?

是否可以使用sed搜索特定的代碼塊並刪除匹配項,並且僅刪除匹配項后的特定行?

例如,如果我有一個像這樣的塊,並且想刪除特殊標記1和僅其后的第二行:

special marker 1
text 1
text 2
text 3

我可以使用sed搜索該塊的實例並得出:

text 1
text 3

我知道類似的命令:

sed -i '/START/,/END/ {/special marker 1/{n;n;N;d;}}' filename;

但是,此命令僅使我具有:

text 1

因此,似乎將下一行操作加倍並刪除。 有什么方法可以修復此命令或以其他方式執行此操作?

告訴sed打印以跳過兩行:

sed -ni '/special marker 1/{n;p;n;n};p' filename

當只需要兩行輸出時,可以將命令替換為

sed -ni '/special marker 1/{n;p;n;n;p}' filename

使用awk您可以執行以下操作:

awk '/special marker 1/{p=NR; next} p && NR==p+2{p=0; next} 1' file
text 1
text 3

嘗試遵循awk解決方案一次。

解決方案1:

awk '/special marker 1/{;if(getline var){print var;if(getline var1){next};next}} 1'   Input_file

解決方案二:

awk '/special marker 1/{getline;if(NF){print};if(NF){;getline};next} 1'  Input_file
sed -i '/START/,/END/ {/special marker 1/{N;N;D};P;d}' filename

暫無
暫無

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

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