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
  • 188,023
  • 17
  • 78
  • 185
steffen
  • 16,138
  • 4
  • 42
  • 81
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
  • 238,783
  • 38
  • 220
  • 352
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
  • 367,544
  • 15
  • 269
  • 518
0

This might work for you (GNU sed):

sed '/^First/,/^Second/!b;/^Second/i New line to be inserted' file
potong
  • 55,640
  • 6
  • 51
  • 83