Linux bulk search and replace

Doing a bulk search and replace across a set of files is actually surprisingly easy. sed is the key. It has a flag – i that will modify the files passed to it in-place.

$ sed -e 's/TextToFind/Replacement/' -i file1 file2 file3

Tie this power with either grep -l . [Thanks to Steve for pointing out a mistake in the following, now corrected]

$ grep -l TextToFind * |xargs sed -e 's/TextToFind/Replacement/' -i

or find

$ find . -exec sed -e 's/TextToFind/Replacement' -i {} ;

If there are multiple changes you want to make, just put them all into a file and pass it in via the -f flag.

file: replacements.patterns

s/TextToFind1/Replacement1/
s/TextToFind2/Replacement2/
s/TextToFind3/Replacement3/

and the command, using find to iterate through all files in the current directory and subdirectories.

find . -exec sed -f replacements.patterns -i {} ;

et voila – hope it helps.

3 thoughts on “Linux bulk search and replace

  1. Thanks – this was exactly what i was looking for, didn’t want to use perl for something i knew could be done via the command line.

    Cheers Steve.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s