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
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
2 thoughts on “sed: perform search and replace only on specific lines (not globally)”
what about if I have multiple lines starting with “two” and I want to replace “one” in 4th line where the line starts with “two”
” I have two lines
two is the lucky number
two times two is four
–>two one zero
two one zero minus one”
this is my text file and I want to replace “one” in the line that has arrow mark
Thank you, very useful.