Find and Replace Text Recursively with Bash

Linux/Unix based platforms have a variety of CLI tools which are incredibly useful. I had a scenario where I needed to update a path reference in various configuration files, fortunately this can be accomplished using a single command:

grep -rl 'foo' . | xargs -l1 sed -i 's/foo/bar/g'

Note: Forward slashes must be escaped from your find and replace strings passed to sed, e.g.

cd /etc/apache2
grep -rl '/etc/apache' conf | xargs sed -i 's/\/etc\/apache/\/etc\/apache2/g'

The above command omits the -l1 argument to xargs. This executes slightly faster as all matching paths are sent to sed at once rather than constructing a foreach loop. If you expect a lot of files to match your search string you’ll want to pass the -l1 argument to avoid a too many arguments error from sed.