Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed command to replace first occurrence in file is not working

Tags:

regex

sed

awk

I am trying to replace first string occurrence in file. e.g. Trying to replace first foo with linux.

sample.txt

Hi foo bar
This is again foo bar.

Command:

sed '0,/foo/s//linux/' sample.txt

Actual output from above command (basically no change)

Hi foo bar
This is again foo bar.

My expected output is as below

Hi linux bar
This is again foo bar.

Could anyone please help here?

like image 416
Ajay Kedare Avatar asked Sep 18 '25 05:09

Ajay Kedare


1 Answers

/tmp/test.txt

Hi foo bar!
This is again foo bar

Use the following sed commando to replace only the first orrouance of the search-string;

sed -e '1 s/foo/linux/; t' -e '1,// s//linux/' /tmp/test.txt

Result:

Hi linux bar!
This is again foo bar

  • Terminal output + OSX version

  • Terminal output; first foo on 3th line

like image 60
0stone0 Avatar answered Sep 19 '25 21:09

0stone0