Perl command line search and replace

Moderator: cah

Post Reply
cah
General of the Army / Fleet Admiral / General of the Air Force
General of the Army / Fleet Admiral / General of the Air Force
Posts: 1342
Joined: Sun Aug 17, 2008 5:05 am

Perl command line search and replace

Post by cah »

It is handy to search and replace strings in a file by Perl from command line.
Here is the syntax:

Code: Select all

# perl -i.bak -p -e"s/old/new/g" filename
-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.

Code: Select all

# perl -e ‘print “Hello World\n”‘
-p option, adds loops around your -e code.It creates code like this:

Code: Select all

LINE:
while (<>) {
# your code goes here
} continue {
print or die “-p destination: $!\n”;
}
-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:

Code: Select all

# perl -i -pe "s/PHP/Perl/g" file.txt
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:

Code: Select all

# perl -i.bak -pe "s/PHP/Perl/g" file.txt
NOTE: Using double-quote (") can use variables in the replacement command. Using single-quote (') can not.
CAH, The Great
Post Reply