Menu

Find and replace text in multiple files

There are many ways to do this. This one is my very simple.

###### Find & Replace in Multiple Files in current Directory #######
#grep -rl "old_string" . | xargs sed -i 's/old_string/new_string/g'
###Find & Replace in Multiple Files recursively under parent directory ###
#grep -rli 'old-word' * | xargs -i@ sed -i 's/old-word/new-word/g' @

What is happening :

grep -rl: search recursively, and only print the files that contain “old_string”
grep -r: –recursive, recursively read all files under each directory.
grep -l: –print-with-matches, prints the name of each file that has a match, instead of printing matching lines.
grep -i: –ignore-case.

xargs: take the output of the grep command and make it the input of the next command (ie, the sed command)
xargs -i@ ~command contains @~: a placeholder for the argument to be used in a specific position in the ~command~, the @ sign is a placeholder which could replaced by any string.

sed -i: edit files in place, without backups.
sed -i ‘s/old_string/new_string/g’: search and replace, within each file, old_string by new_string
sed s/regexp/replacement/: substitute string matching regexp with replacement.
sed s/regexp/replacement/g: global, make the substitution for each match instead of only the first match.

******************************************************************************************************************************

Also :

To replace a string in multiple files you can use:

grep -rl string1 somedir/ | xargs sed -i 's/string1/string2/g'

E.g.

grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'
END.

Loading

Categories:   Linux

Comments