Admin Books

DOWNLOAD Free e-Books for Linux Admin Servers :

Bash using Perl to Search and Replace words, recursively in the directory


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




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

perl -pi -w -e 's/search/replace/g;' *.c


-p loop
-i means edit in-place
-w write warnings
-e means execute the following line of code.


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