Technix
Technology Weblog

Perl commandline search and replace


There are many times when we need to search and replace certain words from files. Doing it manually will be very time consuming. One way to do it is using VI ( my favorite editor !) search n’ replace.

The better option is using perl command line search and replace option. The syntax is the following.

# perl -i.bak -p -e’s/old/new/g’ filename

s/old/new/g

what this does is searches for pattern “old” and replace it pattern “new”.The g option in does the serch n replace globally in the file, otherwise perl searches and replaces only the first instance of the pattern.


Lets explain the options used.

-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.

# perl -e ‘print “Hello World\n”‘

-p option, adds loops around your -e code.It creates code like this:

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:

# 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:

# perl -i.bak -pe ‘s/PHP/Perl/g’ file.txt
About these ads

One Response to “Perl commandline search and replace”


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: