这是示例文件:
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)
这应该适合你
sed -e 's_^all: .*_& anotherthing_'
Run Code Online (Sandbox Code Playgroud)
使用s命令(替换),您可以搜索满足正则表达式的行.在上面的命令中,&代表匹配的字符串.
如果文本$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)
这是使用 sed 的另一个简单解决方案。
$ sed -i 's/all.*/& anotherthing/g' filename.txt
Run Code Online (Sandbox Code Playgroud)
解释:
all.* 表示所有以“all”开头的行。
& 代表匹配(即以'all'开头的完整行)
然后 sed 用后者替换前者并附加“另一个”词
在bash中:
while read -r line ; do
[[ $line == all:* ]] && line+=" anotherthing"
echo "$line"
done < filename
Run Code Online (Sandbox Code Playgroud)
awk 解决方法:
awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file
Run Code Online (Sandbox Code Playgroud)
简单地说:如果该行以all打印该行加上“其他内容”开头,则仅打印该行。
| 归档时间: |
|
| 查看次数: |
141707 次 |
| 最近记录: |