http://qs321.pair.com?node_id=11108347


in reply to Batch file renaming - on identical name, keep only most recent file, based on dates

jcb beat me to the point about collisions from different users. (Edit: it's late here and I got things reversed in my head. No need for the reverse for the sort.) Here is a simple solution that works except it will clobber any collisions between users with the user with the lowest highest number. This solution takes a reverse sort of the filenames and then uses File::Copy::move to rename them so that the newest collision file is the last one to be renamed. If you specify what to do by user collisions this could be modified to watch for the user number.

Perl has a built in rename function but the documentation suggests using File::Copy::move since it is more portable across operating systems.

use warnings; use strict; use File::Copy; use File::Glob ':glob'; mkdir 'test' unless -d 'test'; #foreach( reverse sort glob( "*_Table_*.pdf" ) ){ foreach( sort glob( "*_Table_*.pdf" ) ){ print "$_\n"; my $newname = $_; $newname =~ s/^[0-9_]+//; print "--$newname\n"; ## using copy for testing. copy $_, "./test/$newname" or print "Error copying <$_> $!\n"; #move $_, "$newname" or print "Error renaming <$_> $!\n"; } __DATA__ test files: 8_2007_5_22_15_34_23_Table_-_2007522_XYZ_W3.pdf 8_2007_5_22_22_34_12_Table_-_2007522_XYZ_W3.pdf 7_2007_5_22_16_35_23_Table_-_2007522_XYZ_W3.pdf 7_2007_5_22_23_36_12_Table_-_2007522_XYZ_W3.pdf output file: Table_-_2007522_XYZ_W3.pdf

Edit: I forgot to add the program output. Also, I had an extra file in my test files.

8_2007_5_22_22_34_12_Table_-_2007522_XYZ_W3.pdf --Table_-_2007522_XYZ_W3.pdf 8_2007_5_22_15_34_23_Table_-_2007522_XYZ_W3.pdf --Table_-_2007522_XYZ_W3.pdf 7_2007_5_22_22_34_12_Table_-_2007522_XYZ_W3.pdf --Table_-_2007522_XYZ_W3.pdf 7_2007_5_22_15_34_23_Table_-_2007522_XYZ_W3.pdf --Table_-_2007522_XYZ_W3.pdf 7_2007_12_22_15_34_23_Table_-_20071222_XYZ_W3.pdf --Table_-_20071222_XYZ_W3.pdf

Edit: updated output without reverse sort.

7_2007_12_22_15_34_23_Table_-_20071222_XYZ_W3.pdf --Table_-_20071222_XYZ_W3.pdf 7_2007_5_22_15_34_23_Table_-_2007522_XYZ_W3.pdf --Table_-_2007522_XYZ_W3.pdf 7_2007_5_22_22_34_12_Table_-_2007522_XYZ_W3.pdf --Table_-_2007522_XYZ_W3.pdf 8_2007_5_22_15_34_23_Table_-_2007522_XYZ_W3.pdf --Table_-_2007522_XYZ_W3.pdf 8_2007_5_22_22_34_12_Table_-_2007522_XYZ_W3.pdf --Table_-_2007522_XYZ_W3.pdf