Search code examples
regexperlgreedy

A perl script that worked on Snow Leopard No Longer Works On Lion


I used to take a arbitrary set of files on my Desktop in the format of:

Screen Shot 2011-11-08 at 8.10.23 AM.png

Screen Shot 2011-11-08 at 8.08.57 AM.png

run a Perl script on them and rename them to

SS-2011-11-08 at 8.10.23 AM.png

SS-2011-11-08 at 8.08.57 AM.png

This stopped working and no rename happens. Now that I have to change it, I would like it to change to:

ss-2011.11.08.at.8.10.23.AM.png

ss-2011.11.08.at.8.08.57.AM.png

  • replace "Screen Shot" as that exact case always to "ss"
  • replace all - to .
  • replace all spaces to .

I know it has to do with greediness, but I didn't write this and no matter how much fiddling I do I can't seem to get it to work. I have used perl all of a few hours in my life. I think I could do this in php in a few lines, but would like to learn how to keep it in perl because it's always good to be able to debug. I have looked up the regs formatting rules and they are not applying. Either something is screwy in Mac OS X Lion, or Snow Leopard was allowing things to happen that shouldn't.

Thank you all!

Here is what I have so far:

 #!/usr/bin/perl -w

 chdir( "/Users/me/Desktop" ) or die;
 my @files = ();
 print "after my \@files array\n";
 print @files;

 while ( <*> ) {
    push @files, $_ if m!^Screen Shot (.*) at (.*)\.png!;
 }


 foreach my $f ( @files ) {
    my $new = $f;
    $new =~ s!^SS (.*) at (.*)\.png!ss-$1\_$2.png!;
    print "$f -> $new\n";
    rename ( $f, $new ) or die;
 }

Solution

  • Just change the replacement to this

    $new =~ s/Screen\.Shot\.(.*)\.at\.(.*)/ss-$1.at.$2/;
    

    and add another replacements before it:

    $new =~ s/[- ]/./g;  # Replace all dashes and spaces to dots