簡體   English   中英

sed 在匹配模式后有條件地附加到行

[英]sed conditionally append to line after matching pattern

我有一個文件(測試),其中包含需要編輯的以下內容。

測試

foo:
bar:hello

我目前正在使用 sed 來匹配模式並將字符串附加到行尾。

sed -ie "/^bar/ s/$/,there" test

這給了我預期的輸出,即

foo:
bar:hello,there

但問題是,當行不以:結尾時,逗號 (,) 應該在那里。 否則它會變成這樣:

sed -ie "/^foo/ s/$/,there" test

輸出:

foo:,there
bar:hello

要求:

foo:there
bar:hello

那么是否可以通過任何方式檢查模式,在匹配檢查行的最后一個字符后,根據最后一個字符,在行尾附加一個字符串。

PS:我無法安裝單獨的包。

保持簡單,只需使用 awk:

$ awk '/^foo/{$0 = $0 (/:$/ ? "" : ",") "there"} 1' file
foo:there
bar:hello

$ awk '/^bar/{$0 = $0 (/:$/ ? "" : ",") "there"} 1' file
foo:
bar:hello,there

注意所有原始字符串( foobar )、 :,$和替換文本( there )都是如何只指定一次的? 這是您在軟件中想要的東西之一 - 最小的冗余。

以上將在任何 UNIX 機器上的任何 shell 中使用任何 awk 工作。

這是在成功替換后使用t來分支離開第二個s///命令的一種方法:

$ cat test
foo:
bar:
bar:hello
bar:
bar:hello
bar:
bar:hello

$ sed '/^bar/ {s/:$/:there/;t;s/$/, there/}' test 
foo:
bar:there
bar:hello, there
bar:there
bar:hello, there
bar:there
bar:hello, there

sed 命令前面的模式是您的條件。 您應該知道您可以為 sed 指定多個 -e 命令。

這是您的代碼,但我忽略了 foo 和 bar。 我只關注最后一個字符:

sed -i -e '/[^:]$/s/$/,there/' -e '/:$/s/$/there/' test

/[^:]$/ 是行尾不是冒號的任何字符。 /:$/ 是它的補碼(任何以冒號結尾的行)。

結果如下:

$ sed  -e '/[^:]$/s/$/,there/' -e '/:$/s/$/there/' test
foo:there
bar:hello,there

為兩者嘗試 gnu sed,

sed -E '/^(foo|bar)/ s/:$/&there/;n; s/[^:]$/&,there/' test

暫無
暫無

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

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