Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed to change string in a file only once

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.

like image 347
lxyu Avatar asked Nov 10 '11 14:11

lxyu


2 Answers

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
like image 92
Felix Rabe Avatar answered Sep 21 '22 10:09

Felix Rabe


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.

like image 43
accuya Avatar answered Sep 25 '22 10:09

accuya