假设我有两个文件foo和bar。我想用文件bar的内容替换foo 中的字符串“ this is test ” 。我怎样才能使用单衬sed做到这一点?
我用过了:
sed -i.bak 's/this is test/$(cat bar)\n/g' foo
Run Code Online (Sandbox Code Playgroud)
但是字符串被替换为文字$(cat bar)
而不是bar
. 我曾尝试使用引号,但结果保持不变。
就引用而言,Radu 的回答是正确的。现在的问题是可以说我的 bar 文件包含:
this
is
a
test
file
Run Code Online (Sandbox Code Playgroud)
现在,如果我运行该命令,则会出现错误:
sed: -e 表达式 #1, char 9: 未终止的 `s' 命令
18 次。
以下命令应该适用于您想要的:
sed "s/this is test/$(cat bar)/" foo
Run Code Online (Sandbox Code Playgroud)
如果foo
包含多于一行,则可以使用:
sed "s/this is test/$(sed -e 's/[\&/]/\\&/g' -e 's/$/\\n/' bar | tr -d '\n')/" foo
Run Code Online (Sandbox Code Playgroud)
或者:
sed -e '/this is a test/{r bar' -e 'd}' foo
Run Code Online (Sandbox Code Playgroud)
最后两个命令的来源:用其他文件的内容替换文件中的模式
要更改foo
文件,请使用sed -i
.
单程:
sed -e '/this is test/r bar' -e '/this is test/d' foo
Run Code Online (Sandbox Code Playgroud)
示例结果:
$ cat bar
12
23
$ cat foo
ab
this is test
cd
this is test
ef
$ sed -e '/this is test/r bar' -e '/this is test/d' foo
ab
12
23
cd
12
23
ef
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
17782 次 |
最近记录: |