
如何sed
在匹配後刪除第二行(或任何數字),但不包括匹配和中間的行?
例如:
Enter command below
> login
Command valid
Enter your password at the below prompt
Remember to make sure no-one is looking at your screen
> mysecretword
Password accepted
我只想刪除“> mysecretword”行,因為它是“在下面的提示下輸入您的密碼”行之後的兩行。我無法使用絕對行號位置,因為匹配可能會在文件開始後出現任意行數。
在線搜索我發現了很多類似的解決方案sed '/Enter your password.*/,+3d' filex
,但這也會刪除“輸入您的密碼...”行和以下行,這不是我想要的。我只想刪除一行,即一場比賽後的一定數量的行。
我如何使用sed
(或任何其他常用工具)來做到這一點?
答案1
也許
sed '/^Enter your password/ {
n
n
d
}' file
或等價:
$ sed '/^Enter your password/ {n;n;d;}' file
Enter command below
> login
Command valid
Enter your password at the below prompt
Remember to make sure no-one is looking at your screen
Password accepted
答案2
對於一般情況,請參閱 Ed Morton 的精彩回答:使用 sed 或 awk 列印符合匹配模式的行 。
d) 在某個正規表示式之後列印第 N 筆記錄以外的所有記錄:
awk 'c&&!--c{next}/regexp/{c=N}1' file
申請給定的輸入
$ awk 'c && !--c{next} /^Enter your password/{c=2} 1' ip.txt
Enter command below
> login
Command valid
Enter your password at the below prompt
Remember to make sure no-one is looking at your screen
Password accepted
/^Enter your password/{c=2} 1
這c
是要忽略的匹配後的第 n 行,1
用於列印輸入記錄c && !--c{next}
is&&
短路運算符,因此只要c
計算結果為 false,c
就不會遞減。設定為一個值後c
,只要沒有達到就會遞減0
答案3
sed '/Enter your password.*/{N;p;N;d;}' file