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.


Leave a Reply

Your email will not be published. Name and Email fields are required.

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=""> <strike> <strong>