sed: perform search and replace only on specific lines (not globally)

By default when we perform search and replace action using sed, that is done globally within a file. Although if you have a line number you can perform the replace based on the line number but what if you have a file where you don't know the line number?Let us got through different examples where you can perform such search and replace based on string match but only on the specific lines

Below is my sample file

# cat /tmp/file
four five six
one
seve eight nine
one two three
one
ten eleven twelve
one

 

Perform search and replace based on line number

In my sample file I have multiple instances of word "one" but I would like my search and replace regex to work only on the 4th line

To do the same use below regex

# sed -e '4s/one/replaced/g' /tmp/file
four five six
one
seve eight nine
replaced two three
one
ten eleven twelve
one

Here as you see I have given my line number along with the substitute regex, so the can be replaced with any other line number where you want to perform your replacement

 

Perform search and replace based on a specific string match

Using a line number is one way but still not the best way, the easier way is if you already know a string which exists n the line where you want to perform the replacement. For eg in my sample file I would like to replace the word 'one' on the line which has string'two'

Observe the below regex

# sed -e '/two/s/one/replaced/g' /tmp/file
four five six
one
seve eight nine
replaced two three
one
ten eleven twelve
one

As you see with the 'substitute' regex I have provided the string which it should search first before performing the requested action. So even when my file had 3 instances of 'one', the replace was performed only on the line having 'two'

The above regex can be combined with other meta characters to improvise the task

Suppose if there are multiple instances of 'two' in the file but you would like to perform replacement only on the line which starts with 'two'

# sed -e '/^two/s/one/replaced/g' /tmp/file

To perform a replace on a line which ends with 'two'

# sed -e '/two$/s/one/replaced/g' /tmp/file

 

Leave a Comment