sed 从文件加载替代品

Sam*_*Sam 10 sed text-processing

我正在尝试使用 sed 将文件中的模式替换为另一个文件的完整内容。

目前我正在使用:

sed "s/PATTERN/`cat replacement.txt`/g" "openfile.txt" > "output.txt"
Run Code Online (Sandbox Code Playgroud)

但是,如果替换文件包含任何字符,例如', ", 或者/由于输入未经过清理而开始出现错误。

我一直在尝试使用本指南来帮助我,但我发现很难遵循。如果我尝试建议的r file命令,我只会得到一个字符串。

解决这个问题的最佳方法是什么?

Ram*_*esh 6

应该对你有用。由于您已指定文件中有',/"字符,因此我没有投票以重复关闭。所以,我做了如下测试。

我有file1以下内容。

cat file1
ramesh' has " and /
in this file
and trying
"to replace'
the contents in 
/other file.
Run Code Online (Sandbox Code Playgroud)

现在,file2如下。

cat file2
This is file2
PATTERN 
After pattern contents go here. 
Run Code Online (Sandbox Code Playgroud)

根据共享链接,我创建了script.sed如下内容。

cat script.sed
/PATTERN/ {
  r file1
  d
}
Run Code Online (Sandbox Code Playgroud)

现在,当我以 as 运行命令时sed -f script.sed file2,我得到的输出为,

This is file2
ramesh' has " and /
in this file
and trying
"to replace'
the contents in 
/other file.
After pattern contents go here. 
Run Code Online (Sandbox Code Playgroud)

编辑:这也适用于文件中的多个模式。

  • 请注意,它不会将 `PATTERN` 替换为文件内容,而是将包含 PATTERN 的任何整行替换为文件内容。 (3认同)