Tuesday, September 21, 2010

Perl & Bash: Mass Substitutions from the Command Line

Today I found myself in a situation where I had to do the same global substitution for every file in a directory. I considered writing a script to handle it, but I wanted to try using a Perl one-liner to get the job done.

Given a directory containing a file with the following contents:

  This is a XML file
This is a XML file
I can substitute every occurence of XML with text using:
  $ perl -i -pe 's/XML/text/g' file1.xml
Afterwards, the file now reads:
  This is a text file
This is a text file
If I wanted to do the substitution for every file in the current directory, I can wrap the command in a bash for loop:
  $ for i in `ls`; do perl -i -pe 's/XML/text/g' $i; done

This isn't revolutionary by any means, but its harder for me to forget this technique if I post it here.

1 comment:

  1. You can also do a similar thing inside a file using vi.

    :%s/oldtext/newtext/g

    ReplyDelete