Perl Command-Line Options
It might be troublesome to write perl program for each task, perl command line is a better option for simple tasks.
Below are a few examples:
1) 'Hello world'
perl -e 'print "Hello World\n"'
Note: Option '-e' allows you to run perl in command line
2) Simple in-place search and replace
Replace all 'five' with '5' for all lines in the file ‘test.txt’
perl -p -i -e 's/five/5/g' test.txt
remove ^M in file
perl -p -i -e 's/\r//g' filename
Note: Option '-p -i -e' is usually used together for file in-place editing line by line
Option '-p' allows perl to process the file line by line
Option '-i' allows perl to do in-place editing
3) Embed shell command into perl command line
link all files whose names are inside file_list from folder 'temp' to current folder.
perl -n -e 'if(/(\w+)/) { `ln -s temp/$1 .` ;}' file_list
Note:
Option '-n -e' is usually used together for file processing (non in-place editing) line by line
4) Pipeline shell command with perl command line to process multiple files
Rename all files whose name end with "_old.s" to "_new.s", i.e. test_old.s to test_new.s
ls *_old.s | perl -n -e 'if (/(\w+)_old\.s/) {`mv ${1}_old.s ${1}_new.s`}'
Rename all files whose name end with
grep new file* -l | perl -n -e 'if(/(\w+)/) {`perl -p -i -e 's/new/old/' $1`}'
5) Perl command line with evaluation
Prepend line numbers to all lines start with digit
perl -0777 -p -i -e '$num=-1;s/\n(\d+)/$num++;"\nline$num $1"/eg' test
for example:
original file:
// comment 0
// comment 1
0001100
0001000
//comment 2
new file:
// comment 0
// comment 1
line0 0001100
line1 0001000
//comment 2
Note:
'/e' is used for evaluation
option '-0777' is used to treat the whole file content as a single line with new line in original file as '\n'
The replacement text should always be in double quote 's/\n(\d+)/$num++;"\nline$num $1"/eg'
6) Perl command line inside perl script
Perl script will perform one round of variable replacement before perl command line. To prevent perl script from
performing variable replacement, system command with single quote should be used
system("perl", "-p", "-i", "-e", 's!feature inst_(\d+)\.(I\d+ trans)!feature inst_$1\.'.$lut_feature_add.'!', '--',
'uut_and_err_subuut_2.mif');
Note:
Single quote is used around 's!!!'
$1 will not be replaced by perl script, $1 will refer to matched content '(\d+)' in perl command line
In order to pass variable from perl script to perl command line: need to place variable outside single quote and
join with dot '.', i.e. 's!aaa!'.$variable.'bbb!'
Delimiters 's!!!' is used instead of 's///'or 's{}{}' to avoid error when file containing '/' or '{}'