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

查看:17
本文介绍了使用 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

我想在 FirstSecond 之间添加 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.

要执行此操作,无论字符大小写如何,请按照 使用中的建议使用 I 标记在某些模式前添加文本时忽略大小写 sed:

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天全站免登陆