• tal
    link
    fedilink
    English
    arrow-up
    1
    ·
    19 hours ago

    A Perl program to convert the number of digits in the first numeric field that appears in a list of filenames.

    source
    #!/usr/bin/perl -w
    # numberit.pl
    # Converts between number formats (number of leading zeros) in numbers in title names
    # Usage: <number of digits> filelist
    
    $digits = shift (@ARGV);
    
    if ($digits > -1)
    {
        foreach $oldName (@ARGV)
        {
            $newName = $digitValue = $oldName;
    
            if ($digitValue =~ m/\//) {
              $digitValue =~ m/^(.*\/[^0-9\/]*)([0-9]+)([^\/]*)$/;
              $prefix = $1;
              $postfix = $3;
              if (!defined($prefix)) {
                $prefix = "";
              }
    
              $digitFormatted = sprintf("%0${digits}d", $2);
    
            } else {
              $digitValue =~ m/^([^0-9]*)([0-9]+)([^\/]*)$/;
              $prefix = $1;
              $postfix = $3;
              if (!defined($prefix)) {
                $prefix = "";
              }
    
              $digitFormatted = sprintf("%0${digits}d", $2);
    
    
            }
    
            if ($digitValue) {
              $newName = $prefix . $digitFormatted . $postfix;
              rename($oldName, $newName);
            }
          }
    }
    

    Looks something like:

    $ touch a1.mp3
    $ touch a2.mp3
    $ numberit.pl 3 *
    $ ls
    a001.mp3  a002.mp3
    $ numberit.pl 2 *
    $ ls
    a01.mp3  a02.mp3
    $