regexawksed

sed command to replace first occurrence in file is not working


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?


Solution

  • /tmp/test.txt

    Hi foo bar!
    This is again foo bar
    

    Use the following 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