如何添加到包含sed或awk模式的行的末尾?

yas*_*sar 81 bash awk sed

这是示例文件:

somestuff...
all: thing otherthing
some other stuff
Run Code Online (Sandbox Code Playgroud)

我想要做的是添加到以这样开头的行all::

somestuff...
all: thing otherthing anotherthing
some other stuff
Run Code Online (Sandbox Code Playgroud)

use*_*882 159

这适合我

sed '/^all:/ s/$/ anotherthing/' file
Run Code Online (Sandbox Code Playgroud)

第一部分是要查找的模式,第二部分是$用于行尾的普通sed替换.

如果要在此过程中更改文件,请使用-i选项

sed -i '/^all:/ s/$/ anotherthing/' file
Run Code Online (Sandbox Code Playgroud)

或者您可以将其重定向到另一个文件

sed '/^all:/ s/$/ anotherthing/' file > output
Run Code Online (Sandbox Code Playgroud)

  • 在 Mac OSX 上,对于 `-i` 选项,我必须这样做:`sed -i '' -e '/^all:/ s/$/ anotherthing/' file` (2认同)

izi*_*dor 9

这应该适合你

sed -e 's_^all: .*_& anotherthing_'
Run Code Online (Sandbox Code Playgroud)

使用s命令(替换),您可以搜索满足正则表达式的行.在上面的命令中,&代表匹配的字符串.

  • 只有这个命令适用于Python Fabric的sed().谢谢. (3认同)

fed*_*qui 7

如果文本$0符合条件,您可以将文本附加到awk中:

awk '/^all:/ {$0=$0" anotherthing"} 1' file
Run Code Online (Sandbox Code Playgroud)

说明

  • /patt/ {...}如果该行与给定的模式匹配patt,则执行其中描述的操作{}.
  • 在这种情况下:/^all:/ {$0=$0" anotherthing"}如果行开始(由^)表示all:,则追加anotherthing到该行.
  • 1作为一个真实条件,触发默认操作awk:打印当前行(print $0).这将始终发生,因此它将打印原始行或修改后的行.

测试

对于您的给定输入,它返回:

somestuff...
all: thing otherthing anotherthing
some other stuff
Run Code Online (Sandbox Code Playgroud)

请注意,您还可以提供要附加在变量中的文本:

$ awk -v mytext=" EXTRA TEXT" '/^all:/ {$0=$0mytext} 1' file
somestuff...
all: thing otherthing EXTRA TEXT
some other stuff
Run Code Online (Sandbox Code Playgroud)


che*_*huk 7

这是使用 sed 的另一个简单解决方案。

$ sed -i 's/all.*/& anotherthing/g' filename.txt
Run Code Online (Sandbox Code Playgroud)

解释:

all.* 表示所有以“all”开头的行。

& 代表匹配(即以'all'开头的完整行)

然后 sed 用后者替换前者并附加“另一个”词


gle*_*man 6

在bash中:

while read -r line ; do
    [[ $line == all:* ]] && line+=" anotherthing"
    echo "$line"
done < filename
Run Code Online (Sandbox Code Playgroud)


Man*_*lio 5

awk 解决方法:

awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file
Run Code Online (Sandbox Code Playgroud)

简单地说:如果该行以all打印该行加上“其他内容”开头,则仅打印该行。

  • 您可以将其缩短为:`awk '$1=="all:" {$(NF+1)="anotherthing"} 1'` (4认同)
  • @Prometheus,awk 脚本由“条件{动作}”对组成。如果省略“条件”,则对每条记录执行操作。如果省略了 `{actions}`,并且条件评估为 *true*(数字 `1` 就是这种情况),则默认操作是打印当前记录。 (2认同)