如何使用sed或awk在包含某个模式的行末添加内容?

98

这是一个示例文件:

somestuff...
all: thing otherthing
some other stuff

我想做的是像这样添加到以 all: 开始的行:

somestuff...
all: thing otherthing anotherthing
some other stuff
6个回答

189

这对我来说可行

sed '/^all:/ s/$/ anotherthing/' file

第一部分是用于查找的模式,第二部分是一个普通的sed替换操作,使用$表示行末。

如果你想在过程中更改文件,请使用-i选项。

sed -i '/^all:/ s/$/ anotherthing/' file

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

sed '/^all:/ s/$/ anotherthing/' file > output

仅仅添加一些内容会导致新的一行,替换是正确的方法。 - zhy
2
在Mac OSX上,对于-i选项,我必须这样做:sed -i'' -e'/^all:/ s/$/ anotherthing/' file - Mahdi

19

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

awk '/^all:/ {$0=$0" anotherthing"} 1' file

解释

  • /patt/ {...} 如果该行符合由patt给出的模式,则执行{}中描述的操作。
  • 在这个例子中:/^all:/ {$0=$0" anotherthing"}如果该行以all:开头(由^代表),则将anotherthing附加到该行末尾。
  • 1作为真条件,触发awk的默认操作:打印当前行(print $0)。这将始终发生,因此它将打印原始行或修改后的行。

测试

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

somestuff...
all: thing otherthing anotherthing
some other stuff

请注意,您也可以将要添加的文本放入变量中:

$ awk -v mytext=" EXTRA TEXT" '/^all:/ {$0=$0mytext} 1' file
somestuff...
all: thing otherthing EXTRA TEXT
some other stuff

在 Solaris 上,您将会得到这个错误:awk: can't set $0 - ceving
@ceving 然后你可以使用 /usr/xpg4/bin/awk,它是“好的” awk。 - fedorqui

10

这应该对你有用

sed -e 's_^all: .*_& anotherthing_'

使用 s 命令(替换)你可以查找满足正则表达式的行。在上面的命令中,& 代表匹配到的字符串。


sed:-e 表达式 #1,第21个字符:s 的未知选项 - Mehdi

9

这里有另一种使用sed的简单解决方案。

$ sed -i 's/all.*/& anotherthing/g' filename.txt

解释:

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

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

然后,sed将前者替换为后者,并附加' anotherthing'单词。


6

在Bash中:

while read -r line ; do
    [[ $line == all:* ]] && line+=" anotherthing"
    echo "$line"
done < filename

5
使用awk的解决方案:
awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file

简而言之:如果行以all开头,则打印该行加上"anotherthing",否则仅打印该行。

4
可以将其简化为:awk '$1=="all:" {$(NF+1)="anotherthing"} 1' - glenn jackman
2
@Prometheus,awk脚本由“条件{操作}”对组成。如果省略了“条件”,则会为每个记录执行操作。如果省略了“{操作}”,并且条件评估为true(这是数字“1”的情况),则默认操作是打印当前记录。 - glenn jackman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接