Thursday - August 12, 2004
handy perl script

If you want to search and replace text among lots of files, Perl can make your life a lot simpler. Here is a script to replace the string ‘old_text’ with ‘new_text’ in any file ending with .txt. The script would have to be run from the same directory as the files which have the text you want replaced.

#!/usr/bin/perl

@files = <*.txt>;

foreach $file ( @files )
{
    system( "perl -p -i -e 's/old_text/new_text/g' $file" );
}

In order to use this code, copy it to a file and save it, then run the following command on the file.

chmod 755 <filename>




  1. If you have the GNU version of sed, it’s alot easier to just

    sed -i ’s/old_text/new_text/’ *.txt

      » Comment by Anonymous on August 12, 2004 @ 7:16 am
  2. That’s a good point.

    I tend to use a perl script when I use regular expressions to match and modify the strings instead of simple text to text.

    Also, you can use a one-liner in perl with:

    perl -p -i -e ’s/old_text/new_text/g;’

      » Comment by dan on August 12, 2004 @ 9:27 am
  3. It seems odd to me to make a perl system call calling perl. There are other ways to replace the text, but as Perl is very flexible, this works too.

      » Comment by Cameron on August 12, 2004 @ 12:09 pm
  4. A little script that goes around replacing text in a large number of files? I for one can’t think or anything that could go hideously, hideously wrong with that? :-)

      » Comment by Steve on August 12, 2004 @ 6:12 pm
  5. It makes life a whole lot easier when the alternative is doing it by hand.

      » Comment by dan on August 12, 2004 @ 9:18 pm
  6. Horribly dangerous, but I’ve used a variation of that myself:

    perl -p -i -e ’s/foo/bar/gi’ find . -name ‘*.html’ -print

      » Comment by Andy Baio on August 16, 2004 @ 4:33 pm
  7. One thing you can do to lessen the chance of making a horrid mistake is to add an extension to the -i option (like .bak). That way at least you maintain the original and can diff the two files to see what got changed.

      » Comment by dan on August 18, 2004 @ 10:14 pm


Post a comment










# of readers
- home
meta
comics
news links
other links

about me
blog archives
docs
entertainment
experiences
funny lists
humor
intellectual
interests
mefi
music
opinions
photos
web designs
tools
webmaster help

Sign up
Enter your e-mail address to be notified of new posts



Search blog archives

Calendar
August 2004
S M T W T F S
« Jul   Sep »
1234567
891011121314
15161718192021
22232425262728
293031  



Random quote
(View all quotes)
"Know women, know pain, no women, no pain."










Licensed under Creative Commons
(?) Choose theme:  X X X X X X


W3CCSS
Loaded in 0.1424 seconds