Linux 在特定模式匹配后插入文件内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16715373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:00:16  来源:igfitidea点击:

Insert contents of a file after specific pattern match

regexlinuxsed

提问by Satish

I want to insert file content at specific pattern match. The following is an example: add file2.txtcontent in file1.txtbetween <tag>and </tag>.

我想在特定模式匹配时插入文件内容。下面是一个例子:在和之间添加file2.txt内容。file1.txt<tag></tag>

file1.txt

file1.txt

<html>
<body>
<tag>
</tag>
</body>
</html>

file2.txt

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>

采纳答案by Birei

Try following command:

尝试以下命令:

sed '/<tag>/ r file2.txt' file1.txt

It yields:

它产生:

<html>
<body>
<tag>
Hello world
</tag>
</body>
</html>


EDITfor explanation why your command doesn't work as you want: The r filenamecommand adds its content at the end of the current cycle or when next input line is read. And you are using the Ncommand which doesn't print anything but reads next line, so at that time Hello worldis printed and after that the normal stream of lines.

编辑解释为什么您的命令不能按您的意愿工作:该r filename命令在当前周期结束时或读取下一个输入行时添加其内容。并且您使用的N命令除了读取下一行之外不打印任何内容,因此当时Hello world会打印,然后是正常的行流。

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.

在我的情况下,它读取 line with <tag>,然后结束循环,因此打印该行并在它之后打印文件的内容并继续读取直到结束。