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

前端之家收集整理的这篇文章主要介绍了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

解决方法@H_502_22@
由于/ 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.f2er.com/linux/393346.html

猜你在找的Linux相关文章