簡體   English   中英

在sed中的相同匹配項上執行多個命令

[英]execute multiple commands on the same match in sed

我知道我可以針對sed中的匹配運行命令,如下所示:

$ cat file
line1
line2
line3
line4

$ sed -e "/^line2/ s/^/# /" file
line1
# line2
line3
line4

是否可以在同一匹配項上運行多個命令,例如s/^/#/s/$/ # invalid/

我嘗試將兩者都添加,但出現錯誤:

$ sed -e "/^line2/ s/^/# / s/$/ # /" file
sed: -e expression #1, char 18: unknown option to `s'

我嘗試使用; 但這似乎放棄了初始匹配並在輸入的每一行上執行:

$ sed -e "/^line2/ s/^/# / ; s/$/ # /" file
line1 #
# line2 #
line3 #
line4 #

EDIT2:如果您非常希望在滿足條件時執行多條語句,則可以按以下方式使用{..}塊語句。(剛剛看到@Tiw在注釋中也建議了相同的內容。)

sed '/^line2/ {s/^/#/; s/$/ # invalid/}'  Input_file


編輯:在此處添加1 sed更多解決方案。 (我簡單地把其起始線line2在存儲緩沖器\\1然后簡單而把取代的/ NEW_VALUE添加#之前和附加# invalid后)

sed '/^line2/s/\(.*\)/# \1 # invalid/'  Input_file


您可以嘗試以下嗎?

sed "/^line2/ s/^/# /;/^line2/s/$/ # invalid/"  Input_file

什么是你嘗試發生的事情,只是進行簡單地替代其每行發生的事情,不論它要么從開始line2或沒有,所以當你替換之前,給這個條件應該工作,然后。

您可以嘗試使用擴展的正則表達式:

sed -r -e '/^line2/ s/(.*)/# \1 #/' file

您不需要多個命令,只需替換以line2開頭的行:

sed "s/^line2.*/# & #/" file

這可能對您有用(GNU sed):

sed '/^line2/!b;s/^/.../;s/$/.../' file

在這里,正則表達式使用!取反! 命令和b命令本身分支到所有sed命令的末尾。 也許更簡單的例子是:

sed ' /^lines/bjumphere;bjumpthere;:jumphere;s/^/.../;s/$/.../;:jumpthere' file

當然上面也可以寫成:

sed '/^line2/{s/^/.../;s/$/.../}' file

當編寫一個以換行符結尾的襯線(例如iacrRwW命令)並且需要其他命令時,可以為sed腳本的每個部分調用-e選項,例如:

sed -e '/^line2/{i\a couple of lines\ninserted before "line2"' -e '}' file

也可以這樣寫:

sed '/^line2/i\a couple of lines\ninserted before "line2"' file

如果有要被執行沒有后續sed命令,但是如果line2需要被太刪除:

sed -e '/^line2/b;!i\a couple of lines\ninserted before "line2 then line2 deleted"' -e 'd' file

但是,更好的方法是使用c命令。

sed '/^line2/c\a line changed and a line\nappended for "line2"' file

暫無
暫無

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

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