我正在尝试使用 sed 将一个文件中的模式替换为另一个文件的完整内容。
目前我正在使用:
sed "s/PATTERN/`cat replacement.txt`/g" "openfile.txt" > "output.txt"
但是,如果替换文件包含任何字符,例如'
、"
、 或/
我开始收到错误,因为输入未经过清理。
我一直在尝试使用本指南来帮助我,但我发现很难理解。如果我尝试建议的r file
命令,我只会得到一个字符串。
解决这个问题的最佳方法是什么?
答案1
这应该为你工作。我没有投票关闭作为重复,因为你已经指定你的文件中有'
,/
和字符。"
所以,我做了如下测试。
我有file1
如下内容。
cat file1
ramesh' has " and /
in this file
and trying
"to replace'
the contents in
/other file.
现在,file2
如下。
cat file2
This is file2
PATTERN
After pattern contents go here.
根据共享链接,我创建了script.sed
如下内容。
cat script.sed
/PATTERN/ {
r file1
d
}
现在,当我运行命令 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.
编辑:这也适用于文件中的多个模式。
答案2
如果您需要awk
解决方案,可以使用如下所示的解决方案。
awk '/PATTERN/{system("cat file1");next}1' file2
测试
cat file1
ramesh' has " and /
in this file
and trying
"to replace'
the contents in
/other file.
现在,我有file2
如下。
cat file2
This is file2
PATTERN
After pattern contents go here.
PATTERN
现在,我使用上面提到的awk
命令。
输出:
This is file2
ramesh' has " and /
in this file
and trying
"to replace'
the contents in
/other file.
After pattern contents go here.
ramesh' has " and /
in this file
and trying
"to replace'
the contents in
/other file.
参考
答案3
在:
sed "s/PATTERN/`cat replacement.txt`/g" "openfile.txt"
'
应该"
不是问题。这些并不是特别的sed
。应该有问题的是&
、\
和/
换行符。您可以使用另一个sed
命令来转义它们:
sed "s/PATTERN/$(sed 's@[/\&]@\\&@g;$!s/$/\\/' replacement.txt)/g" openfile.txt
请注意,它删除了 中的尾随换行符replacement.txt
。如果这不是你想要的,你可以这样做
replacement=$(sed 's@[/\&]@\\&@g;s/$/\\/' replacement.txt; echo .)
replacement=${replacement%.}
sed "s/PATTERN/$replacement/g" openfile.txt
答案4
使用 GNU,sed
您可以在脚本的任何位置执行您喜欢的e
操作。cat
与r
- 不同的是,它安排生产线周期结束时的输出(这可能非常令人沮丧!),e
的工作方式类似于i
or c
,它立即写入其输出。以下是其使用的一些示例:
printf %s\\n 'these are some words' \
'that will each appear' \
'on their own line' |
sed 's/.*words/echo & ; cat file/e'
these are some words
these
are
some
more
words
that
are
stored
in
a
file
that will each appear
on their own line
以下是您可以如何使用它:
printf %s\\n 'these are some words' \
'that will each appear' \
'on their own line' |
sed 's/\(.*\)\n*words/\1\n&/;//P;s//\ncat file/ep;s/.*\n//'
these are some
these
are
some
more
words
that
are
stored
in
a
file
that will each appear
on their own line