Tuesday, May 18, 2010

Unix find and replace text within all files within a directory

SkyHi @ Tuesday, May 18, 2010

To replace all instances of a string in a directory (subdirectories included) do:


Code:


perl -e "s/FIND/REPLACE/g;" -pi.save $(find path/to/DIRECTORY -type f)






The above will make a backup temp file of your original

If you do not want a temp file with the .save extension then do:




Code:


perl -e "s/FIND/REPLACE/g;" -pi $(find path/to/DIRECTORY -type f)






--------------------

Example:

You want to replace all instances of the word "design" with "dezine" in the directory /public_html/company/info



you can execute the command from document root as


Code:


perl -e "s/design/dezine/g;" -pi.save $(find public_html/company/info -type f)






or you can execute the command from public_html/company/ (a directory above) as:


Code:


perl -e "s/design/dezine/g;" -pi.save $(find info -type f)






------------------------------



The above commands will search all files (.gif, .jpg, .htm, .html, .txt) so you might see some error messages "Can't open *.gif", etc)



Simplified



To search just files of type, .htm without a backup file in the current directory only (no subdirectories) you could use:




Code:


perl -pi -e 's/design/dezine/g' *.htm







# *****************************************************************************************
# find_and_replace_in_files.sh
# This script does a recursive, case sensitive directory search and replace of files
# To make a case insensitive search replace, use the -i switch in the grep call
# uses a startdirectory parameter so that you can run it outside of specified directory - else this script will modify itself!
# *****************************************************************************************

!/bin/bash
# **************** Change Variables Here ************
startdirectory="/home/gare/tmp/tmp2"
searchterm="search"
replaceterm="replaceTerm"
# **********************************************************

echo "******************************************"
echo "* Search and Replace in Files Version .1 *"
echo "******************************************"

for file in $(grep -l -R $searchterm $startdirectory)
do
sed -e "s/$searchterm/$replaceterm/ig" $file > /tmp/tempfile.tmp
mv /tmp/tempfile.tmp $file
echo "Modified: " $file
done


echo " *** Yay! All Done! *** "








REFERENCES
http://forums.devshed.com/unix-help-35/unix-find-and-replace-text-within-all-files-within-a-146179.html