[LA.pm] Numbering files

Clay Irving clay at panix.com
Sun May 4 15:02:41 CDT 2003


On Sun, May 04, 2003 at 12:40:16PM -0700, Ron Smith wrote:

>    I have a group of files in a directory as follows:
> 
>    file.1
>    file.10
>    file.11
>    file.12
>    file.13
>    file.14
>    file.15
>    file.2
>    file.3
>    file.4
>    file.5
>    file.6
>    file.7
>    file.8
>    file.9
> 
>    How would I go about adding a leadin '0' to the files numbered 1-9 to
>    make the files list in order like the following:
> 
> 
>    file.01
>    file.02
>    file.03
>    file.04
>    file.05
>    file.06
>    file.07
>    file.08
>    file.09
>    file.10
>    file.11
>    file.12
>    file.13
>    file.14
>    file.15

There are many ways. Here's one:

   #!/usr/local/bin/perl5.6.1 
   
   while (<DATA>) {
       chomp;
       ($name, $ext) = split /\./;                     # Split on the .
       if ($ext < 10) {                                # If the file extension 
                                                       # is less than 10
           $ext = "0$ext";                             # Add a leading 0
       }
       push @files, "$name.$ext";                      # Push into an array
   }
   
   @sorted_files = sort { uc($a) cmp uc($b) } @files;  # Sort the array
   
   for(@sorted_files) {                                # Print 
       print "$_\n";
   }
   
   __DATA__
   file.1
   file.10
   file.11
   file.12
   file.13
   file.14
   file.15
   file.2
   file.3
   file.4
   file.5
   file.6
   file.7
   file.8
   file.9
   
Result:

   file.01
   file.02
   file.03
   file.04
   file.05
   file.06
   file.07
   file.08
   file.09
   file.10
   file.11
   file.12
   file.13
   file.14
   file.15

-- 
Clay Irving <clay at panix.com>
I want to die peacefully, in my sleep, like my grandfather, not
screaming, terrified, like his passengers. 



More information about the Losangeles-pm mailing list