[英]Use sed to delete line, and the one below if it contains 1 pattern, but not another
找到了一些類似於我想要的示例,但它們對我不起作用,或者通過評論來判斷其他示例。
我要這個
#Hello my name is Chris
next line of random txt
#Hello my name is Bob
next line of random txt
Hello Ana is my name #
next line of random txt
Another Line
成為這個
#Hello my name is Chris
next line of random txt
Hello Ana is my name #
next line of random txt
Another Line
包含“#”但不包含“ Chris”或“ Ana”的行以及它們下面的行將被刪除。
給定輸入:
#Hello my name is Chris
next line of random txt 1
#Hello my name is Bob
next line of random txt 2
Hello Ana is my name #
next line of random txt 3
Another Line
腳本之一:
sed -e '/#/ { /Chris/b' -e '/Ana/b' -e 'N; d; }' data
或腳本:
sed -E \
-e '/#/ {
/(Chris|Ana)/b
N
d
}' \
data
產生:
#Hello my name is Chris
next line of random txt 1
Hello Ana is my name #
next line of random txt 3
Another Line
這似乎符合您的規格。 第一個甚至沒有使用擴展正則表達式(ERE)語法,因此它具有最大的可移植性,但是第二個表明可以輕松地對其進行修改以使用ERE語法。 使用BSD sed
,在branch( b
)命令之后不能使用分號; 接下來將要發生在另一行或另一個-e
參數中。 沒有顯式標簽的b
表示“分支到腳本結尾”。
這可能對您有用(GNU sed):
sed '/Chris\|Ana/b;/#/!b;$!N;d' file
如果一行包含Chris
或Ana
break,請不要進行進一步處理並按正常打印。 同樣,如果一行不包含#
。 如果當前行不是最后一行,請獲取下一行並刪除兩者。 否則,如果它是最后一行,也將其刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.