在特定模式匹配后插入文件的内容 [英] Insert contents of a file after specific pattern match
问题描述
我想在特定模式匹配处插入文件内容.下面是一个例子:在
和之间的
.file1.txt
中添加file2.txt
内容;
I want to insert file content at specific pattern match. The following is an example: add file2.txt
content in file1.txt
between <tag>
and </tag>
.
file1.txt
<html>
<body>
<tag>
</tag>
</body>
</html>
file2.txt
Hello world!!
我尝试了以下操作,但没有成功.
I have tried following and it didn't work.
# sed "/<tag>/ {
h
r file2.txt
g
N
}" file1.txt
<html>
<body>
Hello World!!
<tag>
</tag>
</body>
</html>
推荐答案
尝试以下命令:
sed '/<tag>/ r file2.txt' file1.txt
它产生:
<html>
<body>
<tag>
Hello world
</tag>
</body>
</html>
<小时>
EDIT 解释为什么您的命令无法按您的意愿工作: r filename
命令在当前循环结束时或下一个输入行时添加其内容已读.并且您正在使用 N
命令,该命令不打印任何内容,但会读取下一行,因此此时会打印 Hello world
,然后是正常的行流.
EDIT for explanation why your command doesn't work as you want: The r filename
command adds its content at the end of the current cycle or when next input line is read. And you are using the N
command which doesn't print anything but reads next line, so at that time Hello world
is printed and after that the normal stream of lines.
在我的例子中,它读取带有
的行,然后结束循环,因此打印该行并在它之后打印文件的内容并继续读取直到结束.
In my case, it reads line with <tag>
, then ends cycle, so prints the line and after it the content of the file and carry on reading until the end.
这篇关于在特定模式匹配后插入文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!