How to replace the first occurrence only (of a string match) in a file, using sed

Finding a solution for this was bordering on ridiculous, no matter how I put it… “replace using non greedy”, “replace only one instance of a string”, “replace first string match only” I struggled to find an answer. The man page had no information on this either. After a while I came up with the following solution.

sed '0,/this/s//to_that/' filename.txt

It was able to replace the first occurrence of the string “only” as I wanted (regardless of which line it was on etc), however I had no idea how I did it. After I had finished, I Tweeted for some assistance on how this actually works, a colleague sent me the following link which is quite comprehensive.

http://www.grymoire.com/Unix/Sed.html

Advertisements

7 thoughts on “How to replace the first occurrence only (of a string match) in a file, using sed

  1. sed ‘0,/match/s//to_that/’ filename.txt

    sed ‘0,/match/’ = From zero-th line to ‘match’ string line
    sed ‘0,/match/s//replace/’ = replace the match with the ‘replace’ string

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s