Perl

From ZENWorks Wiki

Jump to: navigation, search

How to replace a string in a file with another string

Combine perl -e with the command line editing capability of modern shells and you can, write, test, and debug in record time.

The -p option tells Perl to act as a stream editor similar to sed and awk.

This could be used to replace hundreds of files with the same string

Image:file.gifFile: file_to_edit.txt
I want to replace Sarah Howell with Sarah Jennings
Perl
Linux:> perl -p -i.org -e 's/Howell/Jennings/g' Example.txt

This command will also create a file Image:folder.pngExample.txt.org as a backup copy.

The "s" makes perl search for Howell and the action "g" makes the search global. This means that the RegEx engine will continue searching on the same line after the first match, instead of stopping at the first match and then going to the next line.

You can also use word boundaries, otherwise we might replace Howell's instead of only replacing Howell. Throw \b into the mix for word boundaries. The command would look like
Linux:> perl -p -i.org -e 's/\bHowell\b/Jennings/g' Example.txt


Additional information can be found at Image:stock_internet.pnghttp://www.linux.com/feature/52709

Personal tools