Friday, May 27, 2011

Perl command line execution

Following parameters are very important when executing the perl commands from the command line. Following is the general format.

perl <options> -e '<perl commands>' <input file>

Following options are very important.

-i.bak ==> reads the input file and backs it up (as <filename>.bak) and all the output will be written to the input file. The backup extension can be customised. However this option is useful only when used with the below options

-n  ==> Each line of the input file is passed to the expression as $_.

-p ==> Same as -n. Each line of the input file is passed as $_ to the expression. And adds a implicit print $_ at the end of the expression. If the expression modified $_ ( search & replace for e.g.) then the modified string will be written.

Ideally-p or -n will be used along with -i. 
For e.g. I have my input file
>cat temp.txt
1
2
3
4
5
>perl -n -e 'print "My $_"' temp.txt
My 1
My 2
My 3
My 4
My 5
>perl -p -e 'print "My $_"' temp.txt
My 1
1
My 2
2
My 3
3
My 4
4
My 5
5
>perl -pi.bak -e 's/1/ONE/' temp.txt
>cat temp.txt
ONE
2
3
4
5
>cat temp.txt.bak
1
2
3
4
5


No comments:

Post a Comment