Friday, September 21, 2012

Find and Replace work in Multiple Files

Easy Search and Replace word in Multiple Files on Linux Command Line


I was trying to find a solution to do a find & replace word across multiple files which was purely command line based. There are plenty of scripts out there which will accomplish this but I needed a single line command. After some google searches and some experimentation I came up with this snippet.

Syntax : [root@server ~]# grep -lr -e '<oldword>' * | xargs sed -i 's/<oldword>/<newword>/g'

Example : [root@server ~]# grep -lr -e 'country' * | xargs sed -i 's/country/India/g'

This command broken down:
  • grep for the word in a files, use recursion (to find files in sub directories), and list only file matches
  • xargs passes the results from the grep command to sed
  • sed -i uses a regular expression (regex) to evaluate the change: s (search) / search word / target word / g (global replace)
Find & Replace word of specific files:
I want to replace the word “country” with “India” from those files which are having “.php” extension. To do so use the following command :
Syntax : [root@server ~]# find . -name “*.php” -print | xargs sed -i 's/old word/new word/g'
Example : [root@server ~]# find . -name “*.php” -print | xargs sed -i 's/country/India/g'

It looks bit complicated but quite simple. There are three components to the command.
  1. find . -name "*.php" -print – Find all files (recursively) which has “.php” in the file and print them out. This will give you output like this:
    ./file.php
    ./includes/test.php
    ./classes/class.php
  2. xargs- This command is used when you want to pass a lot of arguments to one command. xargs will combine the single line output of find and run commands with multiple
    arguments, multiple times if necessary to avoid the max chars per line limit. In this case we combine xargs with sed
  3. sed -i 's/country/India/g' – Stream Editor is a tool which should be in every sys admin’s toolkit. In this case every occurence of “country” is replaced by “India” in all the files found using the “find” command. Sed simply parses input and applies certain text transformations to it.

No comments: