Sed : Replace pattern on every second newline?

sed 's/pattern/replacement/2'

Will replace the second occurrence on every line that has the pattern.


if you have GNU sed:

sed '1~2N ; s/pattern/replacement/2'

Starting from line one 1, the line after it will be added to the pattern space N then the s command will replace the second occurrence of the pattern. then sed will move two lines down ~2 and repeat.


see https://stackoverflow.com/questions/5858200/sed-replace-every-nth-occurrence

The solution uses awk rather than sed, but "use the right tool for the job". It may or may not be possible to do in sed but, even if it is, it will be a lot easier in a tool like awk or perl.


The simple interpretation:

On the first line that contains at least one occurrence of PATTERN you want to ignore it and print the line as-is. On the second line that contains at least one occurrence of PATTERN you want to replace the first instance of PATTERN with REPLACEMENT. On the third line that contains at least one occurrence of PATTERN you want to print the line as-is. On the fourth line that contains at least one occurrence of PATTERN you want to replace the first instance of PATTERN with REPLACEMENT. And so on. Lines that do not match PATTERN should be printed without change.

This can be easily done with Sed like so:

sed -e '/PATTERN/ { :inside' -e 'n;s//REPLACEMENT/;t' -e 'b inside' -e '}'

Or, with less whitespace and a shorter label:

sed -e '/PATTERN/{:i' -e 'n;s//REPLACEMENT/;t' -e 'b i' -e '}'

EDIT: I just reread the question and spotted the harder interpretation:

Replace the second occurrence of PATTERN in the entire document with REPLACEMENT, whether it occurs on the same line as the first occurrence or not. Leave the first and third occurrences unaltered. Etc.

I believe this can be done with Sed as well, though it's MUCH trickier and I believe it is dependent on the regular expression to be used. I will try to work something out and post it, but I will let this answer stand with the simple version above for now.

Tags:

Replace

Sed