Sed Examples: Search and Replace on Linux

Last updated:

Usage of sed is closely linked to that of find. I'll try to keep examples relevant to sed only.

To see different ways to use find, look at Linux find examples

Search and replace with regular expressions

sed uses a set of regexes different from grep and Perl

For example, replace all digits with dashes in the target file:

$ sed -i -r 's/[0-9]/-/g' /path/to/my/file.txt

Search/replace static strings

$ sed -i 's/foo/bar/' /path/to/my/file.txt

Search/replace using regular expressions and matches

In order to use the results of a match in the "search" part in the "replace" part of the sed command, use "\"+match_number. For example, to add a 'X' to the end of all numbers in a file:

$ sed -r -i 's/([0-9]+)/\1X/g' my_file.txt

In this example, I've used \1 to match the first match group (match groups are stuff that's between parentheses). If there were more, you could also use \2,\3 and so on to represent the next matches.

Escaping single Quotes

Use double quotes as delimiters:

$ sed "s/''/'foobar'/g" my_file.txt

Replace a whole line that contains a pattern

For example, replace the line that matches "FOO BAR" anywhere in it with "The quick brown fox jumps over the lazy dog":

$ sed -i '/FOO BAR/c\The quick brown fox jumps over the lazy dog' my_file.txt

So if you had something like this:

Lorem ipsum dolor sit amet
consectetur FOO BAR adipiscing elit
Nullam a dui sapien.

It becomes this:

Lorem ipsum dolor sit amet
The quick brown fox jumps over the lazy dog
Nullam a dui sapien.

Replacing newlines (\n) using sed

sed is line-based, so it's hard for it to work with newlines. Use tr instead

This is a workaround to allow you to replace newlines with whitespace using sed.

$ sed ':a;N;$!ba;s/\n/ /g' my_file.txt

Search/replace a string in current directory and under

For example, to replace all occurrences of "foo" with "bar" in all files in the current directory and under:

$ find . -name "*.*" -type f | xargs sed -i 's/foo/bar/g'

HEADS-UP: "*.*" means all files! This also includes files like those under Code Versioning Tools, like SVN or GIT. Running this command on a directory that includes these files may break your repositories! use with caution!


Dialogue & Discussion