Re: failed substitution



Beginner wrote:
Hi,

Hello,

I have a number of jpegs I wanted to rename. I wrote a short script
to do it but the new file name is not always generated correctly. The
script should find the last letter in the filename (before the
extension) and substitute it for '_a'.

If you look at the results below you'll see that 'a' and 'b' fail but
'c' worked. I don't understand why.

DSC00092a.jpg -> DSC00092a.jpg a
DSC00093b.jpg -> DSC00093b.jpg b
DSC00094c.jpg -> DSC00094_a.jpg c
DSC00095d.jpg -> DSC00095d.jpg d
DSC00096e.jpg -> DSC00096e.jpg e
DSC00097f.jpg -> DSC00097f.jpg f
DSC00098g.jpg -> DSC00098g.jpg g
DSC00099h.jpg -> DSC00099h.jpg h
DSC00100i.jpg -> DSC00100i.jpg i
DSC00101j.jpg -> DSC00101_a.jpg j
DSC00102k.jpg -> DSC00102_a.jpg k
DSC00103l.jpg -> DSC00103l.jpg l
...snip

Here the script, there isn't much to it. Can anyone explain why the
substitute fails?


#!/bin/perl
# Active State 5.8.6.811

use strict;
use warnings;
use File::Basename;

my $dir = 'D:/Temp/jpegs/thumbs/';
my @files = glob("${dir}*.jpg");

foreach my $f (@files) {
(my $l) = ($f =~ /([a-z]|[a-z][a-z])\.jpg/);

Perl's alternation always quits when the first alternative matches so in your
example ([a-z]) and ([a-z]|[a-z][a-z]) are equivalent. Perhaps you meant
([a-z]{1,2}) instead?


(my $new = $f) =~ s/$l/_a/;

$f contains the complete path so you are probably modifying something other
than the file name.

You probably want something like:

( my $new = $f ) =~ s/([a-z]{1,2})(?=\.jpg\z)/_a/;


my $basef = basename($f);
my $basenew = basename($new);
print "$basef -> $basenew $l\n";
}


John
--
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order. -- Larry Wall
.



Relevant Pages

  • Re: using xml to save/open project data
    ... http://www.TransProCalc.org - Free translation project mgmt software ... set filename tk_getOpenfile ... Exec'ing the script you run it as a separate process, your script won't be able to access its vars. ... generating the xml file is easy enough. ...
    (comp.lang.tcl)
  • Re: Help me find 5 mistakes and than solution to thoes mistakes!
    ... > 8:# This script will create links to files from all of the filename ... > 10:# arguments provided on stdin if no filenames provided on command ...
    (Fedora)
  • Re: MIME - scripting and symbol substitutions
    ... This script is creating a text file with a different filename ... symbol called NEWFILENAME (which works, ... MIME from the command line with all options (so normal DCL ...
    (comp.os.vms)
  • Re: virtual server backups
    ... Here is the script. ... 'Save state the virtual machine ... Filename = MyArray) ... Set objVM = Nothing ...
    (microsoft.public.windows.server.general)
  • Help with os.spawnv
    ... I've had to migrate back to Python 2.1 and am now trying to use ... This script gets each Ascii file in the workspace, ... for filename in filenames ...
    (comp.lang.python)