January 09, 2004

I hate Perl! I love Perl!

Today at work I needed to go over a few hundred, possibly over a thousand, files and add a line into each of them. I know I know, there has to be something wrong in the architecture if you need to do something like that, and there is. But what can you do, the code is over ten years old and NOT written by me.

I wasn't going to do that by hand.

I figured I could just use my old, trustworthy Ultraedit (which one of the few shareware programs I've bought) and it's replace-in-files with regular expressions. First, I had a little problem getting XP's sucky Find to work with the type of files I was editing, involving registry changes (it'll soon be time for the last nail in my Windows coffin). Some lines I only needed to change a bit, and that went fine with Ultra-Edit, but to my big surprise, there just wasn't any way insert a new line into multiple files in UltraEdit. I could have done it if Ultraedit had provided more complete support for regular expressions, but after banging my head into a wall for a few hours I had to give up. There were two main problems, Ultraedit neither supports zero-width look ahead nor limiting the search to the first hit.

So I had to find another solution. After a quick, fruitless web search, I couldn't find any applications that would properly insert lines to multiple files, so I had to write it myself. Previous experience told me that Perl is a good choice at this type of things. It also told me that Perl can be a bit painful at times. And oh, how painful it was, once again.

Here's the solution on one line (actually two) to add "blahblahblah" as the first line into each file in the current directory:

perl -pi .bak -e "BEGIN{@ARGV=map glob,@ARGV}/COMPONENT/;print \"blahblahblah\n\" if ($. == 1); close ARGV if eof" *.*

Anyone need any explaining?

I can't believe how messy Perl looks like. I didn't figure out the solution on my own, but found one post on a Perl messaboard, that I needed to modify for Windows. Btw, the post also describes a solution using Sed, which looked much cleaner to me, but I wasn't interested in installing another interpreter just for this. The biggest headache was to get the wildcards in the file name expanded (globbed). Of course, Windows doesn't do that automatically for you (Linux, here I come!). For a Perl one-line-solution to get the wildcards expanded I again Googled it up.

And this is supposed to be fun? Anyway, job done and my hate/love relationship with Perl deepends - on both ends.

Posted by thoughts at 07:45 AM | Comments (0) | TrackBack