Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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).



I found

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

But it replaced every first occurence, not the second.

share|improve this question
up vote 7 down vote accepted

see http://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.

share|improve this answer
Using what i've learn there I maid sed -e 'n;s/2004-2009/6e législature/g' which solved my problem. – Matthieu Riegler Aug 1 '12 at 12:27
that won't get every second occurrence, it will search for your pattern on every second line. i.e. skip the 1st, 3rd, 5th, 7th, etc lines. of course, that might still work for your particular document. – cas Aug 1 '12 at 22:19
Yup I know. that's what I needed actually. – Matthieu Riegler Aug 2 '12 at 0:27

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.

share|improve this answer
I don't want the second but every second. – Matthieu Riegler Aug 1 '12 at 11:45
I have one pattern per line. That won't work. – Matthieu Riegler Aug 1 '12 at 11:53
would've been nice to know that prior. So the pattern happens on line one, two, three and four (etc), and you want to replace the pattern on line two, four, etc? – llua Aug 1 '12 at 12:00
a shorter alternative may be code(sed '1~2s/pattern/replacement/') – jaap Jun 22 '15 at 14:30

One symbol pattern within the one line: sed 's/(a[^a]*)a/\1c/g'

Every second pattern (only one pattern match per line may appear. if two or more matches per one line will appear, only the second one will be replaced)

echo -e "test\nreplace_me\ntest\ntest\nreplace_me\nreplace_me\nreplace_me" | \
sed '/replace_me/{:a;N;/replace_me.*replace_me/!Ta;s/replace_me/replaced/2;}'
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.