Occasionally you need to change the contents of some files easily to save a lot of manual work. In my case it was a server migration, the old IP address of a server was referred to from numerous DNS records. This meant the contents of a couple of hundred Bind zone files would also have to change so that they would reflect the new server address.
This is task that would take way too long to do manually, luckily grep and sed can automate the process. In this post I will show you how to recursively search for and change a string in all files that exist below a directory.
The format for doing a recursive search / replace looks like:
grep -rl ‘search_term’ ./ | xargs sed -i ‘s/search_term/replacement_text/g’
Here we are telling grep to get a list of all the filenames containing the search term contained in files below the current directory. The xargs command then feeds this list to search which will open the files and replace all occurrences of the string with the replacement text provide.
So in my use case where I needed to change all instances of a servers IP address (18.104.22.168) to reflect the IP address of the new server (22.214.171.124) in my existing Bind zone files, I would use:
grep -rl ‘126.96.36.199’ /etc/bind/zones | xargs sed -i ‘s/188.8.131.52/184.108.40.206/g’
That gets the job done, but if your in a production environment another trick is to add an extension after the sed -i flag and a backup will be made of the file with that extension before making the changes i.e
grep -rl ‘220.127.116.11’ /etc/bind/zones | xargs sed -i_backup ‘s/18.104.22.168/22.214.171.124/g’