Short Tip: replace characters in txt files with sed

shell.png
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 least on Fedora it is even required by core system parts like udev.

Advertisements

7 thoughts on “Short Tip: replace characters in txt files with sed”

  1. I’ve grown accustomed to use perl for this kind of thing:

    perl -pi -e ‘s/foo/bar/g’ FILENAMES

    This modifies files in place and allows for reusing matches, e.g.

    perl -pi -e ‘s/G(.*)/K\1/g’

    (maybe ( should be escaped like \(, i’m not quite sure)

  2. I always use something like

    sed -i~ ‘s/foo/bar/’g FILENAME

    which makes a backup of the file with suffix ~. But you can supply nearly everything as a suffix in -i[SUFFIX].

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s