Find and sed: Search and Replace Examples and Tips for 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

[USING FIND] Search/replace a string in all files in current directory and under

-i instructs sed to perform the replacing in the actual file and then save it (needless to say, only do this if you're sure about what you're doing. If you're unsure about the results, run sed without -i option, for that will print the changes on standard output rather than actually doing them in the actual files.)

For example, to replace all occurrences of "foo" with "bar":

$ 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!

[USING FIND] Search and replace file contents using regular expressions

sed uses a set of regexes different from grep and Perl

find can also be neatly used with sed to perform search and replace using regular expressions. In order to replace all occurrences of digits in .txt files with a dash ("-") :

$ find . -name "*.txt" | xargs sed -i -r 's/[0-9]/-/g'

Search/replace static strings

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

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 '0' to the end of all numbers in a file:

$ xargs sed -r -i 's/([0-9]+)/\10/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.

Dialogue & Discussion