Monday, April 13, 2009

Perl for the sysadmin

Sometimes, you need to just change a few characters in a really big text file, but can't stand waiting for your favorite editor (*cough* vi *cough*) to modify it? Why not fix it up with a little perl and regular expression:

[root@delta ~]# perl -i -ne 's/something/else/sg;print;' ./really-big-file

The magic '-i' operator will modify your file inline, so you don't have to open it manually. But wait, there's more! If you're like me, you find that its easy to screw something up, like spelling else 'esle'. Then you just need a backup right? Simple enough, try this on for size:

[root@delta ~]# perl -i.bak -ne 's/something/else/sg;print;' ./really-big-file

What does that do? It makes a backup of your file as really-big-file.bak

Well, now that you know how to modify files inline, guess you can do something a little more daring:

[root@delta ~]# find /home -type f \! \( -perm -u+x -o -perm -g+x -o -perm -o+x \) -exec perl -i -ne 'tr/[a-zA-Z]/[n-za-mN-ZA-M]/;print;' "{}" \;

1 comments:

  1. You can do the same with sed and awk also, for example in sed you can do:

    sed -i.bak 's/something/else/g' filename

    ReplyDelete