global search and replace

Jason Stephenson jason at sigio.com
Tue May 13 10:31:36 EDT 2003


Greg Rundlett wrote:

[Deletia]

> 
> 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?

Global search and replace in Perl is pretty straightforward, provided 
that you understand regular expressions. Even if you don't it will still 
work if what you want to replace is a fixed phrase. Here's an example. 
Let's say that we want to search all the files in a given directory and 
replace the string 'Foo Bar' with 'Bar Foo'. This oneliner will do it:

perl -pi -e 's/Foo Bar/Bar Foo/' *

The -p option tells Perl to run a loop that assumes aditional arguments 
to be files and to open and read those files. The -i option says to edit 
those file "in place," i.e. it saves the output to the input file. 
(Well, actually it save the output to a different file and then renames 
it when it is done.) The -e option specifies a chuck of Perl code to 
run. The 's/Foo Bar/Bar Foo/' is the Perl code we're running which will 
replace the left side with the contents of the right side. (NOTE: The 
way I've written it, the first occurrence of Foo Bar on any given line 
is replaced. If Foo Bar appears more than once on a line, any subsequent 
occurrences are not replaced. In order to replace all occurrences on a 
line add a 'g' after the last '/', like so: 's/Foo Bar/Bar Foo/g'.) The 
*, of course, is the shell wildcard that will match all files and 
subdirectories of the current directory.

You could get more complicated than the above, but if you do, you'll 
likely find yourself rewriting sed(1) in Perl. I highly recommend you 
use sed(1) for this task, it is what it was designed to do. Even a basic 
intro. to sed is beyond what I can put in an email, though I have no 
problem with writing long emails. ;-) Try 'man sed' or 'info sed' to get 
more info. on using sed. O'Reilly also has published a good book on the 
topic, SED AND AWK.

Cheers,
Jason

P.S. Hey, grammar sticklers: I know that commas and periods should go 
inside quotes in written English. I deliberately put them outside in the 
examples above so that the reader would not get confused into thinking 
that the punctuation was part of the code. After all, we are talking 
about Perl. :-)




More information about the gnhlug-discuss mailing list