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

grep -rl ‘’ /etc/bind/zones | xargs sed -i ‘s/’

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 ‘’ /etc/bind/zones | xargs sed -i_backup ‘s/’

Leave a Reply

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