hoopajoo.net
Modifying lots of files
Modifying lots of files
⇐ Back to One Liners

Questions, comments, or corrections? Send me a message.

If you have some changes to do to a lot of files, for example you're moving a section of your website and all cgi-bin links need to become shoppingcart instead, perl can do it easy and make backups for you. In bash you might do something like this:

#!/bin/bash

for FILE in *.html
do
 mv $FILE $FILE.backup
 sed s/cgi-bin/shoppingcart/g $FILE.backup > $FILE
done
But in perl, using the -p switch to do the printing while() loop and the -i switch to instruct perl to edit in place. The whole script above could be done like this as a one-liner in perl:
perl -pi.backup -e 's/cgi-bin/shoppingcart/g' *.html
The -i tells perl to basically move the file to the .extension you specify, and anything printed will go to the original name. The -p means loop over the file and print anything in $_, and -e means execute this code in the while loop. So you basically do the s/// operator then it prints out the changes, and even preserves a .backup file for you!