Madhan
Madhan

Reputation: 21

Search first pattern and search second pattern and then insert a new line above the second pattern

I got stuck with following text processing in a file, such that -> Search the first pattern and then search second pattern and then insert a new line above the second pattern.

File Sample:

some text 1
First-search-text some other text
some text 2
some text 3
Second-search-text

Desired output to be replaced in the file:

some text 1
First-search-text some other text
some text 2
some text 3
New line to be inserted
Second-search-text

any pointers will be great help with awk or sed.

Upvotes: 1

Views: 804

Answers (4)

potong
potong

Reputation: 58578

This might work for you (GNU sed):

sed '/^First/,/^Second/!b;/^Second/i New line to be inserted' file

Upvotes: 0

steffen
steffen

Reputation: 17058

Set a flag on first match, then search for second match with flag set:

 awk '/First-search-text/{f=1}f&&/Second-search-text/{print "New line to be inserted"}1' file

Upvotes: 2

ikegami
ikegami

Reputation: 386676

Insert before every second-match after a first-match:

perl -pe'print "New line\n" if $f && /^Second-search-text/; $f||=/^First-search-text/'

Insert before the first second-match after every first-match:

perl -pe'print "New line\n" if (/^First-search-text/../^Second-search-text/) =~ /E0/'

Specifying file to process to Perl one-liner

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 247210

Using

ed file <<'END_OF_COMMANDS'
/First-search-text/
/Second-search-text/
i
New line to be inserted
.
wq
END_OF_COMMANDS

Upvotes: 2

Related Questions