Category Archives: Perl

Linux: How do I mass find and replace text in files under linux using perl?

Few friends have asked me how to do mass find and replace text in files under linux. There are quite a bit of options in linux to achieve mass replacing of text in files. If you are doing it file by file, you can achieve that in vi by opening, running replace and closing and going to next file. But sometimes that can be very tedious and you would rather do mass replacement on all files containing certain extension. We can do this by using sed or perl. Since most people are familiar with perl (at least most system admins and programmers), I will show you a perl way of doing it which you can use with sed as well if you wish. First step is to get perl to do what we want on one file

perl -w -i -p -e "s/search_text/replace_text/g" filename

-w turns warnings on
-i makes Perl operate on files in-place (if you would like to make backups, use -i.bak, this will save filename.bak files)
-p loops over the whole input
-e specifies Perl expression
filename works on one file at a time

Once we get the results we want, we can now pass it multiple files by doing something like:

perl -w -i -p -e "s/search_text/replace_text/g" *.php

This will search and replace within all php files in the directory you are in.

Now, let us say you want to go through your whole web directory and replace every place where you have “Perl is good” to “Perl is great”, you would use following command:

find /www_root -name "*.php"|xargs perl -w -i -p -e "s/Perl is good/perl is great/g"

find will start at /www_root, look for filenames which have .php extension, xargs takes that filename and passes it to perl as an arguement.

————————————-
DISCLAIMER: Please be smart and use code found on internet carefully. Make backups often. And yeah.. last but not least.. I am not responsible for any damage caused by this posting. Use at your own risk.

Perl: How do I install Perl modules? eg. Installing LWP module for Perl.

The easiest way to install Perl modules is by installing them through “shell”. Let us say that you are trying to install very common module called: LWP

You can test to see if you have LWP installed by typing:
perl -MLWP -le "print(LWP->VERSION)"
If you get something like: Can’t locate LWP.pm in @INC means that you don’t have it installed. To install LWP, type:
perl -MCPAN -eshell
NOTE: most times it is okey for you to accept default answers to questions cpan asks.
You can read through cpan help by typing “h” without the quotes at cpan> prompt.
To continue installing LWP, type:
install Bundle::LWP
After few questions, and some text scrolling, you will have LWP installed. If for some reason you don’t want to do it this way, you can always obtain source for the module you are trying to install and build it from source files. You can obtain these files from CPAN site