7

suggest I have a file example as follows:

c
a
b
a
b
d

and I want to change the first occurance of a to e. Then I do this:

sed -i 's/a/e/' example

and all a changed to e.

So is there any way to make sed only replace once within a file?

Thanks.

lxyu
  • 2,661
  • 5
  • 23
  • 29
  • 4
    possible duplicate: http://stackoverflow.com/questions/148451/how-to-use-sed-to-replace-only-the-first-occurrence-in-a-file – Aziz Nov 10 '11 at 14:48

2 Answers2

12

Applying the information from Aziz' duplicate link to your question, I think this will give you the desired result for your case:

sed -i '0,/a/s//e/' example
Felix Rabe
  • 4,206
  • 4
  • 25
  • 34
5

Applying the information from Aziz' duplicate link to your question, I think this will give you the desired result for your case:

sed -i '0,/a/s//e/' example

Rabe's answer is good. But, adding a space between address range and 's' command makes it more clearer. like this:

sed -i '0,/a/ s//e/' example

And Wilson's version seems redundant.

accuya
  • 1,412
  • 14
  • 14