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

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

本文介绍了特定模式匹配后插入文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以特定的模式匹配插入文件内容.下面是一个示例:在<tag></tag>之间的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>


编辑解释为什么命令无法按您的期望运行: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.

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

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.

这篇关于特定模式匹配后插入文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 08:28