Find and replace a value in multiple files in a directory tree

Written by James McDonald

February 12, 2013

Just had a situation where I need to find and replace a value in multiple html, js, php files starting in /var/www/html and descending to replace all instances.

This worked for me.

fgrep srv-02 * -lR | xargs sed -i.bak -e 's/srv-02/srv-04/g'

Basically the above means use fgrep to get a list of files which contain a match

Use xargs to pass each filename to sed

sed creates a backup of each file with a ‘.bak’ extension and does a global (g) find and replace on the search term



Submit a Comment

Your email address will not be published.

You May Also Like…


Zebra Printer Language The above website has a page where you can enter ZPL and it...

PHP Iterators

Just came across a Youtube talk "Iterators in PHP" by Jake Smith published in 2014 that steps through the many...