xvi_16
xvi_16

Reputation: 135

SED append on next n-th line, not append to next line

How can I get sed to append sometext two line after it find a match?

For example:

text0
text1
text2
text3

after I match text0, I want to append text4 after the next 2 line, that is:

text0
text1
text2
text4
text3

Upvotes: 1

Views: 132

Answers (3)

Jotne
Jotne

Reputation: 41460

I would have used awk for this:

awk '/text0/ {f=NR} f && NR==f+2 {$0=$0RS"text4"}1' file
text0
text1
text2
text4
text3

When pattern is found, set f to current line number.
When f is true and two lines later f && NR==f+2 add new text $0=$0RS"text4".
1 print the result

Upvotes: 1

choroba
choroba

Reputation: 242103

Perl solution:

perl -pe 'push @append, 3 + $. if /text0/;
          shift @append, print "text4\n" if $append[0] == $.;
         ' input.txt > output.txt

You might need some more tweaking if the string is to be appended after the end of the input.

Explanation:

  • $. is the line number.
  • when /text0/ is matched, the line number where the append should happen is pushed into the array @append.
  • when the current line number corresponds to the one at the beginning of the array, the line is printed and the first element of the array is discarded.

It also means it works for overlapping matches and appends.

Upvotes: 1

Wintermute
Wintermute

Reputation: 44063

I'd say:

sed -e '/text0/ { N; N; a text4' -e '}' filename

That is:

/text0/ {  # when finding a line that matches text0
  N        # fetch two more lines
  N
           # and only then append text4
  a text4
}

When using this as a one-liner, it is necessary to split it into two -e options so that the a command doesn't attempt to append a line text4 }.

Alternatively, you could use

sed '/text0/ { N; N; s/$/\ntext4/; }' filename

this avoids using the somewhat unwieldy a command but requires you to escape some metacharacters in the replacement text (such as \ and &).

Upvotes: 2

Related Questions