Skip to content
Blog SED: Shell command to find and replace text inside a directory (multiple files)

SED: Shell command to find and replace text inside a directory (multiple files)

I have been using this command for a long time now. Whenever i am in need of this command, i won’t be remembering the correct syntax. So, i google it each time.
Now, i am gonna write it down here.

sed is a marvelous utility. Unfortunately, most people never learn its real power. The language is very simple, but the documentation is terrible

If you have to replace a string in a file, you can use:

sed -i 's/search/replace/g' filename.txt

The above command (sed) edits the file (filename.txt) in place (-i) and replaces the word “search” with “replace”.
If you want to replace a string in a file and write the output to a new file then it would be like:

sed 's/search/replace/g' filename.txt > newfile.txt

Now, imagine if you have a whole lot of files in a directory and you want to search for a string in all those files and replace it with another.

Lets combine the sed with the find command to do what we need.

find /look_here -type f -exec sed -i 's/search/replace/g' {} \;

If you want to know more about sed and its capabilities, see here.

🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.