Replace Text Recursively with sed

Here is a quick little trick I discovered today when I needed to replace text in multiple files recursively:

grep -rl -e <searchterm> * | xargs sed -i .bak 's/searchterm/newterm/i'

There might be a problem with files that have spaces in the names (because xargs will take a space as the start of a new argument). To solve this problem, you should be able to do something like this:

grep -rl --null -e <searchterm> * |
xargs -0 sed -i .bak 's/searchterm/newterm/i'

If you are using GNU grep, you could also use -Z instead of –null. I happen to be using the BSD version of grep, so -Z isn’t an alias for –null.

Category: Coding, Unix | Tags: , , , , Comment »


Leave a Reply



Back to top