Short Tip: replace characters in txt files with sed
February 27, 2008 — liquidat
When working with txt files or with the shell in general it is sometimes necessary to replace certain chars in existing files. In that cases sed can come in handy:
sed -i 's/foo/bar/g' FILENAME
The -i option makes sure that the changes are saved in the new file - in case you are not sure that sed will work as you expect it you should use it without the option but provide an output filename. The s is for search, the foo is the pattern you are searching the file for, bar is the replacement string and the g flag makes sure that all hits on each line are replaced, not just the first one.
If you have to replace special characters like a dot or a comma, they have to be entered with a backslash to make clear that you mean the chars, not some control command:
sed -i 's/./,/g' *txt
Sed should be available on every standard installation of any distribution. At lesat on Fedora it is even required by core system parts like udev.


