1

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.

Madhan
  • 21
  • 2

4 Answers4

2

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
Ed Morton
  • 172,331
  • 17
  • 70
  • 167
steffen
  • 14,490
  • 3
  • 40
  • 77
2

Using

ed file <<'END_OF_COMMANDS'
/First-search-text/
/Second-search-text/
i
New line to be inserted
.
wq
END_OF_COMMANDS
glenn jackman
  • 223,850
  • 36
  • 205
  • 328
2

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

ikegami
  • 343,984
  • 15
  • 249
  • 495
0

This might work for you (GNU sed):

sed '/^First/,/^Second/!b;/^Second/i New line to be inserted' file
potong
  • 51,370
  • 6
  • 49
  • 80