Search and Replace Text in Files Recursively

 
  find . -type f -name "*.html" -print -exec perl -pi -w -e 's/oldsite.com/newsite.com/g;' {} ;
 

The first part "find . -type f -name "*.html" -print" finds all of the files starting at the currrent directory that end with .html. The "-type f" makes sure that only files are found and not directories. The string that comes after the -name parameter is the filename to find. The -print parameter just prints the the relative path to the found file.

The -exec parameter is used to execute a command with the found file. Everything after the -exec is executed until it reaches ";".

The command that is executed on each file is a perl command that does the find and replace.

 
  perl -pi -w -e 's/oldsite.com/newsite.com/g;'
 

Breakdown of perl command:

-e means execute the following line of code.
-i means edit in-place
-w write warnings
-p loop
Then the part between the single quotes is the line of code witch is a command to find all occurances of oldsite.com and replace it with newsite.com. The periods are reserved characters so they need to be escaped with a back-slash.




No Comments



Leave a comment