Home > Linux > Batch replace text in Linux files using sed

Batch replace text in Linux files using sed

Another very short note on a frequently used Linux tool: sed (short for Stream EDitor). In a nutshell sed manipulates data streams such as text streams. Therefore it can be used to batch replace text across multiple files. sed understands basic regular expressions (BRE) as well as extended regular expressions (ERE, using the -r parameter) inline, therefore is pretty powerful and quick to use on the command line.

General example: text replacement in specific file

sed -e s/oldtext/newtext/g filename

Inside the perl regex “s/…/…/” the s stands for substitute – and you have to escape special characters in oldtext or newtext (e.g. a dot) using a backslash.

Example: convert decimal comma to decimal point in multiple csv files

sed -i s/,/\./g *csv

Some hints (for all options look at the man page of sed)
As mentioned the dot has to be escaped as \.
: don’t write to the stdout but replace text “in place”, therefore directly in the files.
-e add the script (s/…/…/g) to the commands to be executed. You can also add multiple scripts to a single sed command.
s in the script (perl regex) stands for substitute (replace) and g for global: replace all occurrences of commas, not only the first per line.

Categories: Linux Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: