Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

linux - Add text between two patterns in File using sed command

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

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

Desired Output:

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

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 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since /r stands for reading in a file, use:

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

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

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

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.

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

Given these files:

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

Let's run the command:

$ 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...