rename files from alpha to numeric

Discussion in 'Perl Misc' started by jfix, Jun 13, 2005.

  1. jfix

    jfix Guest

    hello,

    I have files whose names start with "parta...." which I'd like to
    rename to "n0001..." where the "a" is transformed to 1, the "b" to 2
    etc. I'm pretty sure there's an easy way where you take the
    character's ascii value and substract the difference plus one (like
    this: asc("a") - 96 = 1, right?)

    sub renameFiles {
    my %part = {'a' => 1, "b" => 2, "c" => 3,
    "d" => 4, "e" => 5, "f" => 6};

    foreach $f (@filelist) {
    $f =~ s{ ### complains about Uninitialised
    ### value in this line
    ^part(.)
    }{
    sprintf("n%03d", $part{$1});
    }xeg;
    print "$f\n";
    }
    }

    I guess this is way too much, and it is very slow (probably evaluating
    the Perl code for each match), but this is my stab, and it doesn't even
    work and I don't even know why.

    thanks for any help,
    Jakob.
     
    jfix, Jun 13, 2005
    #1
    1. Advertisements

  2. jfix

    Jim Keenan Guest

    Assuming that by "it doesn't even work" you mean that no files are
    renamed, I am not surprised. Nothing in the code excerpt you presented
    renames a file; it merely prints something to STDOUT.

    Check out the documentation: perldoc -f rename

    Jim Keenan
     
    Jim Keenan, Jun 13, 2005
    #2
    1. Advertisements

  3. s/^part(\w)/sprintf 'n%03d', ord($1)-96/e for @filelist;
     
    Gunnar Hjalmarsson, Jun 13, 2005
    #3
  4. #! /usr/bin/perl

    use strict;
    use warnings;

    while(<DATA>) {
    if(/^part([a-z])/) {
    printf "n%4.4d\n", ord($1) - ord('a') + 1;
    }
    }

    __END__
    parta
    partc
    partd
    parte
    partb
    partv
    partz

    D:\Home\asu1\UseNet\clpmisc> ttt
    n0001
    n0003
    n0004
    n0005
    n0002
    n0022
    n0026
     
    A. Sinan Unur, Jun 13, 2005
    #4
  5. jfix

    jfix Guest

    Thanks everybody who replied to me. That was exactly what I needed.

    cheers,
    Jakob.
     
    jfix, Jun 14, 2005
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.