微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux – 使用sed命令在File中的两个模式之间添加文本

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

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内容

期望的输出

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

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

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

解决方法

由于/ r代表读取文件,请使用:
sed '/First/r file1.txt' infile.txt

你可以在这里找到一些信息:Reading in a file with the ‘r’ command.

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

要执行此操作,无论字符是什么情况,请使用Use sed with ignore case while adding text before some pattern中建议的I标记

sed 's/first/last/Ig' file

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

要这样做,我会去拿一个标志的awk:

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

原文地址:https://www.jb51.cc/linux/393346.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐