这是一个示例文件:
somestuff...
all: thing otherthing
some other stuff
我想做的是像这样添加到以 all:
开始的行:
somestuff...
all: thing otherthing anotherthing
some other stuff
这对我来说可行
sed '/^all:/ s/$/ anotherthing/' file
第一部分是用于查找的模式,第二部分是一个普通的sed替换操作,使用$
表示行末。
如果你想在过程中更改文件,请使用-i
选项。
sed -i '/^all:/ s/$/ anotherthing/' file
或者您可以将其重定向到另一个文件
sed '/^all:/ s/$/ anotherthing/' file > output
如果符合条件,您可以在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
awk: can't set $0
。 - ceving/usr/xpg4/bin/awk
,它是“好的” awk。 - fedorqui这应该对你有用
sed -e 's_^all: .*_& anotherthing_'
使用 s 命令(替换)你可以查找满足正则表达式的行。在上面的命令中,&
代表匹配到的字符串。
这里有另一种使用sed的简单解决方案。
$ sed -i 's/all.*/& anotherthing/g' filename.txt
解释:
all.* 表示以'all'开头的所有行。
& 代表匹配(即以'all'开头的完整行)。
然后,sed将前者替换为后者,并附加' anotherthing'单词。
在Bash中:
while read -r line ; do
[[ $line == all:* ]] && line+=" anotherthing"
echo "$line"
done < filename
awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file
all
开头,则打印该行加上"anotherthing",否则仅打印该行。awk '$1=="all:" {$(NF+1)="anotherthing"} 1'
。 - glenn jackman
-i
选项,我必须这样做:sed -i'' -e'/^all:/ s/$/ anotherthing/' file
。 - Mahdi