global search and replace
Dan Coutu
coutu at snowy-owl.com
Tue May 13 10:23:46 EDT 2003
Greg Rundlett wrote:
> It has been so long since I used perl, that I have to dig through my
> books and old code snippets even to find and understand the recipes that
> I come across.
>
> How do you do this?
Here's a direct answer to your question. Use a command similar to this:
perl -pi -e "s/foo/bar/g;" list-of-files
You can, of course get all sorts of complex and elegant if you really
want to, since the perl sustitute operation uses regular expressions,
but most of the time the above is enough.
Rules to remember:
the source string, foo in this case, can be a regular expression. So if
it has characters in it like %, *, +, parentheses and back slashes (\)
then you'll need to 'quote' them with a backslash so that they are
intrepreted literally. The replacement string, bar in this case, does
not have this requirement since it is interpreted as a literal string.
You may or may not wish to use modifiers after the third slash. In the
example above I've used g which means to do the search/replace globally
(which in this case means every time it shows up, without the g it would
replace only the *first* match on a given line and the leave the others
on that same line alone.) You might want to use the i modifier to
indicate case insensitive searching.
Hope this helps. More detail is available via 'man perlrequick' and 'man
perlre'.
--
Dan Coutu
Managing Director
Snowy Owl Internet Consulting, LLC
http://www.snowy-owl.com/
More information about the gnhlug-discuss
mailing list