Linux CLI: File Text Search & Replace

magnifying glassOccasionally 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 (220.233.0.5) to reflect the IP address of the new server (61.85.66.100) in my existing Bind zone files, I would use:

grep -rl ‘220.233.0.5’ /etc/bind/zones | xargs sed -i ‘s/220.233.0.5/61.85.66.100/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.233.0.5’ /etc/bind/zones | xargs sed -i_backup ‘s/220.233.0.5/61.85.66.100/g’

Leave a Reply

Your email address will not be published. Required fields are marked *