Perl command line search and replace
Posted: Thu Jun 05, 2014 1:01 pm
It is handy to search and replace strings in a file by Perl from command line.
Here is the syntax:
-e option allows you to define Perl code to be executed by the compiler. For example, it’s not necessary to write a “Hello World” program in Perl when you can just type this at the command line.
-p option, adds loops around your -e code.It creates code like this:
-i option. Actually, Perl renames the input file and reads from this renamed version while writing to a new file with the original name. If -i is given a string argument, then that string is appended to the name of the original version of the file. For example, to change all occurrences of “PHP” to “Perl” in a data file you could write something like this:
Perl reads the input file a line at a time, making the substitution, and then writing the results back to a new file that has the same name as the original file — effectively overwriting it. If you’re not so confident of your Perl abilities you might take a backup of the original file, like this:
NOTE: Using double-quote (") can use variables in the replacement command. Using single-quote (') can not.
Here is the syntax:
Code: Select all
# perl -i.bak -p -e"s/old/new/g" filename
Code: Select all
# perl -e ‘print “Hello World\n”‘
Code: Select all
LINE:
while (<>) {
# your code goes here
} continue {
print or die “-p destination: $!\n”;
}
Code: Select all
# perl -i -pe "s/PHP/Perl/g" file.txt
Code: Select all
# perl -i.bak -pe "s/PHP/Perl/g" file.txt