Perl Search and Replace

Perl can be used to easily parse through files and perform a search and replace. For instance, the following command replaces all occurrences of ‘old’ with ‘new’ in myfile.txt after backing up the original as myfile.txt-OLD:

perl -pi-OLD -e 's/old/new/g' myfile.txt

Here is a description of the switches used according to Perl’s help (perl –help):

  • -p assume loop like -n but print line also, like sed
  • -i[extension] edit <> files in place (makes backup if extension supplied)
  • -e program one line of program (several -e’s allowed, omit programfile)

If you want to get creative, use Perl along with the Linux find command. With the next command, I replace ‘old’ with ‘new’ in all files that end in .html:

find /start/path -type f -name '*.html' -exec perl -pi-OLD -e 's/old/new/g' {} \;

Search and Replace Piped Output

You can also search and replace piped results. In this case, I display /etc/shadow and replace password hashes with ‘HIDDEN’:

sudo cat /etc/shadow | perl -p -e 's/(:)[^:]*/$1HIDDEN/'