[英]How do i delete first 2 lines which match with a text given by me ( using sed )?
我如何刪除與我提供的文本匹配的前 2 行(使用 sed !)
例如:
#file.txt contains following lines :
abc
def
def
abc
abc
def
我想刪除前 2 個“abc”
雖然@EdMorton 指出sed
不是這項工作的最佳工具(如果您想知道為什么,請參閱下面我的答案並將其與awk
代碼進行比較),但我的研究表明,通用問題的解決方案
使用
sed
刪除匹配給定模式的行中出現的“N”到“M”
在我看來確實是一個非常棘手的問題。 關於如何用sed
替換匹配模式的“第 N”次出現,似乎有很多建議,但我發現刪除特定匹配行(或一系列行)是一項復雜得多的工作。
雖然通過在有限狀態機的基礎上編寫“sed 腳本生成器”可以最好地解決 N、M 和模式的任意值的廣義問題,但 OP 提出的特殊情況的解決方案仍然很簡單手動編碼就夠了。 我必須承認,我之前不太熟悉sed
命令語法的復雜性,但我發現這個挑戰對於獲得更多非平凡sed
用法的經驗非常有用。
無論如何,這是我刪除文件中包含“abc”的行的前兩次出現的解決方案。 如果有更簡單的方法,我很想了解它,因為這花了我一些時間。
最后一個警告:這假設 GNU sed
,因為我無法找到 POSIX sed
的解決方案:
sed -n ':1;/abc/{n;b2;};p;$b4;n;b1;:2;/abc/{n;b3;};p;$b4;n;b2;:3;p;$b4;n;b3;:4;q' file
或者,在更詳細的語法中:
sed -n '
# BEGIN - look for first match
:first;
/abc/ {
# First match found. Skip line and jump to second section
n; bsecond;
};
# Line does not match. Print it and quit if end-of-file reached
p; $bend;
# Advance to next line and start over
n; bfirst;
# END - look for first match
# BEGIN - look for second match
:second;
/abc/ {
# Second match found. Skip line and jump to final section
n; bfinal;
}
# Line does not match. Print it and quit if end-of-file reached
p; $bend;
# Advance to next line and start over
n; bsecond;
# END - look for second match
# BEGIN - both matches found; print remaining lines
:final;
# Print line and quit if end-of-file reached
p; $bend;
# Advance to next line and start over
n; bfinal;
# END - print remaining lines
# QUIT
:end;
q;
' file
sed 用於單個行上的簡單替換,僅此而已。 對於其他任何事情,您都應該使用 awk:
$ awk '!(/abc/ && ++c<3)' file
def
def
abc
def
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.