How to replace a text using bash sed command

bash find and replace

Here is how you can replace a text in a file using bash script. You can use the sed command as below to replace the text.

sed -i 's/old-word/new-word/g' sample.txt

In above example you can find the word ‘old-word‘ in file sample.txt and replace it with word ‘new-word‘.

You need to escape ‘/’ character in your words. Here is an example,

sed -i 's/a word with \/ character/replaced word/g' sample.txt

Here is sample output using above code,

original > This file has a word with / character
replaced > This file has replaced word

If you need to create a new file with replaced words you can use following command,

sed -i 's/old-word/new-word/g' sample.txt > sample2.txt

Above code will create a new file with replaced words. This will be helpful if you want to keep the original file untouched.

Image courtesy : Andrew Mason

Enjoyed this article? Share with friends

Subscribe

Subscribe to our email feed and never miss a post

Join Us