Unix bash snippet: global replace text in multiple files

Unlike this overkill solution in python, bash is the best tool for this sort of task. The following script searches all files the current directory and subdirectories, and replaces all instances of text “abc” with text “xyz”.
grep and sed are your friends…

#!/bin/sh
for file in `grep -r -l abc *`
do sed  's/abc/xyz/g'; $file > $file.fixed
echo $file.fixed
done
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s