Linux #3: Search and Replace

Search and Replace text in one File

To search a string in a file and replace all occurrences of it with a different string use sed:

sed -i 's/string/replace/g' file

With this command all occurrences of the text string in the file file will be replaced with replace.

Search and Replace text in all Files in a directory

To replace all occurrences of a string in all files in a directory recursively use sed in combination with find:
find /directory -type f -exec sed -i 's/search/replace/g' {} \;

This post is only meant as a quick reference for those that sometimes forget the syntax for search and replace (me for example. Especially the combination of sed and find is quite long and I never bothered to remember it as I do not use it that often). If you want to know more about sed read this in depth sed tutorial.

Related Posts:

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>