使用sed命令在文件的两个模式之间添加文本 [英] Add text between two patterns in File using sed command

查看:177
本文介绍了使用sed命令在文件的两个模式之间添加文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在两种模式之间添加一些大代码:

I want to add Some large code between two patterns:

File1.txt

This is text to be inserted into the File.

infile.txt

Some Text here
First
Second
Some Text here

我想在 First Second 之间添加 File1.txt 内容:

I want to add File1.txt content between First and Second :

所需的输出:

Some Text here
First
This is text to be inserted into the File.
Second
Some Text here

我可以使用sed命令使用两种模式进行搜索,但是我不知道如何在它们之间添加内容.

I can search using two patterns with sed command ,But I don't have idea how do I add content between them.

sed '/First/,/Second/!d' infile 

推荐答案

由于/r代表读取文件,请使用:

sed '/First/r file1.txt' infile.txt

您可以在此处找到一些信息:用'r读入文件'命令.

You can find some info here: Reading in a file with the 'r' command.

为就地版本添加-i(即sed -i '/First/r file1.txt' infile.txt).

Add -i (that is, sed -i '/First/r file1.txt' infile.txt) for in-place edition.

无论字符大小写如何执行此操作,请按照在不区分大小写的情况下使用sed,而在中建议使用I标记.在某些模式之前添加文本:

To perform this action no matter the case of the characters, use the I mark as suggested in Use sed with ignore case while adding text before some pattern:

sed 's/first/last/Ig' file


如评论中所示,上述解决方案只是在模式之后打印给定的字符串,而不考虑第二个模式.


As indicated in comments, the above solution is just printing a given string after a pattern, without taking into consideration the second pattern.

为此,我会带一个标志的awk:

To do so, I'd go for an awk with a flag:

awk -v data="$(<patt_file)" '/First/ {f=1} /Second/ && f {print data; f=0}1' file

给出以下文件:

$ cat patt_file
This is text to be inserted
$ cat file
Some Text here
First
First
Second
Some Text here
First
Bar

让我们运行命令:

$ awk -v data="$(<patt_file)" '/First/ {f=1} /Second/ && f {print data; f=0}1' file
Some Text here
First                             # <--- no line appended here
First
This is text to be inserted       # <--- line appended here
Second
Some Text here
First                             # <--- no line appended here
Bar

这篇关于使用sed命令在文件的两个模式之间添加文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆