Perl hacks

Posted on mercoledì 10 novembre 2010 by Ivano Binetti

How to replace recursively a word into a file

One of  the most frequent task of a linux engineer is to manipulate words within files. Many times this task can be accomplished with linux basic tools like sed, awk, grep using obviously pipe ('|') to correlate them.
But suppose that you would like to replace recursively one, all or some occurrences of a word into a file without modify the rest of file but only replacing the chosen word(s) and also you want to do this task at command line without use a dedicated script?

The answer is: "You can use Perl!"

Suppose you want replace all the occurrences of the word 'foo' with the word 'dog' within the file 'foo.txt' . You can write at command line:

$ perl -p -i -e "s/foo/dog/g" foo.txt

-p: is like the cycle while(<>){....} to read a file line to line.
-i: without this option the command redirect his output to terminal. With this options the stdout  is redirected to our file.
-e: is the option to specify a command

Simple, not?

Obviously if you want to replace only the first occurrence of 'foo' you need to delete '\g' from the 's///' operator.

The problem is: "ok, I'm able to replace one or all the occurrences of a word, but I would like to replace only some of them, when a particular condition is verified".
The answer is: "don't worry friend, you need only to use the 'm//' operator and a simple if condition within the perl command. Suppose the the condition is the presence of word 'animal'. The command will be:

$ perl -p -i -e "s/foo/dog/g if m/ if m/animal/" foo.txt

To use this command to replace one, some or all the occurrences of a word in many files you can use simply this cycle:


for file in $(find /...); do $ perl -p -i -e "s/foo/dog/g if m/ if m/animal/" $file; done


Enjoy this command!

0 Responses to "Perl hacks":