Magnolia25 has asked for the wisdom of the Perl Monks concerning the following question:

I got some files in directory as below:

000001.OrderID.html 000002.OrderID.cgi 000003.OrderID.pl 000004.OrderID.js 000005.OrderID.txt 000006.OrderID.cgi 000007.OrderID.minus.html OrderID.master

Based on some condition certain files are copied into other directory.

(000003.OrderID.pl & 000007.OrderID.minus.html are not copied)

000001.OrderID.html 000002.OrderID.cgi 000004.OrderID.js 000005.OrderID.txt 000006.OrderID.cgi OrderID.master

What I need is to correct the sequence number of files after they are copied into other directory

000001.OrderID.html ** remain as is 000001.OrderID.html - Should be +ignored for renaming 000002.OrderID.cgi ** remain as is 000002.OrderID.cgi - Should be +ignored for renaming 000004.OrderID.js => 000004.OrderID.js Rename to => 000003.OrderI +D.js 000005.OrderID.txt => 000005.OrderID.txt Rename to => 000004.OrderI +D.txt 000006.OrderID.cgi => 000006.OrderID.cgi Rename to => 000005.OrderI +D.cgi OrderID.master ** OrderID.master Should be ignored for renamin +g

Apparently I am stuck here. Please help.

Replies are listed 'Best First'.
Re: Renaming files sequentially into directory
by hippo (Archbishop) on Sep 18, 2018 at 14:09 UTC

    Simple method (brute force):

    #!/usr/bin/env perl use strict; use warnings; my @files = ( '000001.OrderID.html', '000002.OrderID.cgi', '000004.OrderID.js', '000005.OrderID.txt', '000006.OrderID.cgi', 'OrderID.master' ); my $i = 1; for my $infile (sort grep /^\d{6}\./, @files) { my $repl = sprintf ("%6.6i", $i++); (my $outfile = $infile) =~ s/^\d{6}/$repl/; rename $infile, $outfile; }

    You can replace the initial set-up of @files with a glob.

    Update: comma was absent from penultimate line.

      Thanks hippo for looking at this.

       push (@renamefiles, $outfile);

      Indeed I can see the files renamed now, but 'OrderID.master' file is skipped, I need this file also in my @renamefiles array and name 'OrderID.master'should remain as is

      Also, Instead of pushing the files to @renamefiles , can I do this change in same array @files and check the file name changed in @files array

      Thanks again for your help.

        This is a new feature - there was no mention of it in your original post. So, instead of re-engineering the solution already provided, you can just populate your @renamefiles array with a fresh glob after the renames have completed.