Wiki‎ > ‎

Batch Search and Replace in Multiple Files

posted May 24, 2013, 10:42 PM by Dong Xu   [ updated May 24, 2013, 10:45 PM ]

Two simple, rather elegant, solutions:

perl -pi -w -e ‘s/wrong/right/g;’ *.html
Replaces all instances of ‘wrong’ with ‘right’ in html files within the current working directory.

grep -rl “wrong” /home/jerrywaller  | xargs sed -i ‘s|wrong|right|g’
Recursively replaces ‘wrong’ with ‘right’ within the designated directory.

Just make sure you use plain single and double quotation marks, and not the smart quotes that may show up in the formatting above.  Hat tip to the author and commenters here and here

=============================================================

You could also use find and sed, but I find that this little line of perl works nicely.


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


-e means execute the following line of code.

-i means edit in-place

-w write warnings

-p loop


Example I had the following style sheet in a section:

<link rel="stylesheet" type="text/css" href="../includes/style.css">

and I wanted the following instead:

<link rel="stylesheet" type="text/css" href="admin.css">


As each expression is a regular expression you've got to escape the special characters such as forward slash and .

\.\.\/includes\/style\.css


So the final line of code ends up as

perl -pi -w -e 's/\.\.\/includes\/style\.css/admin\.css/g;' *.php
Comments