Sed Replace – How to Replace Pattern on Every Second Newline

replacesed

Is there a way to tell sed to replace the pattern on every second occurrence? Or at least on every second line? (Sure it's possible with a script, but I was asking myself if sed can do it to).

Edit

I found

sed -e "s/pattern/replacement/g;n"

But it replaced every first occurence, not the second.

Example

Input file:

I have a pattern in each line
Also the second line has the pattern
Another pattern here
And -- you guess it -- a pattern

Desired output:

I have a pattern in each line
Also the second line has the replacement
Another pattern here
And -- you guess it -- a replacement

Best Answer

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.

Related Question