shooter.logo.3

Tuesday,April,05,2005

An easier way to search and replace in UNIX with perl

Why screw around with loops and sed for making changes in a bunch of files???

I'm an old school kind of UNIX admin. I like tools like sed and awk. But that's not to say that I don't appreciate the "easy" way of doing things. For example, I'm sure we're all familiar with this sort of thing:
for each file in *.text
do
sed 's/search/replace/g' <$file >$file.tempfile
mv $file.tempfile $file
done
sed, the stream editor, can't write it's output directly to the file that it's operating on, so you use a tempfile to get around that limitation. However, there is an easier way using our friend Perl:
perl -pi -e 's/search/replace/g' *.text
Here's a breakdown of how that command works:
-p Assumes an input loop around the script. It reads each line of the file
  and outputs it after processing
-i Activates in place editing of files
-e Indicates a single lines script
's/search/replace/g' is the script or command. In this case
                              it's a search and replace regex
*.text the filename(s) to operate on
With a little effort you can create all kinds of custom commands to execute against files on your unix box. Custom grep-like commands allow flexibility you can't get from any flavor of grep. For those unfamiliar with UNIX classics like sed and awk, perl offers you all the functionality (and more) with a tool you may already be somewhat familiar with. Any sysadmin worth her bytes should have at least a minimal amount of experience with Perl. See http://www.perl.org/ and/or the perl manpage for further information...

Feedback (1)
Posted by stevem on 04/05 at 09:47,AM • Category: Geek Speak
Permalink

Share this entry with a friend

Page 1 of 1 pages

Next entry: Marketing?

Previous entry: This Means War!!!

<< Previous Page

Shooter.net Home