Replace characters in txt files with sed and replace commands


linux shell

Yesterday I was writing a shell script and I needed to replace some specific characters inside a txt file on the linux system. So, I started digging about how to do this without any complicated commands and found sed as the most easy way to do it.

If you want to replace “word1″ with “word2″, just run this command:

sed -i 's/word1/word2/g' yourfile.txt
  • The -i option ensures you the changes will be saved in the new file.
  • The s options is used for string search.
  • The g option is used to replace each line is found with the matching word.

If you have to replace special characters like a dot or a comma, you need to escape those with with a backslash:

sed -i 's/./,/g' yourfile.txt

Sed is available on most standard Linux distributions, such as Fedora, CentOS, Ubuntu, Debian, Arch, etc.

If you don’t want to use sed or don’t have it installed on your system, there is a second alternative you can use with the “replace” command.

replace command comes with mysql-sever package and it allows you to replace strings in a simple way, same as sed, for example:

replace "word1" "word2" -- file.txt

If you have any other tips for string replacement on Linux, share it with us :)