Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Batch file renaming - on identical name, keep only most recent file, based on dates

by shadowsong (Pilgrim)
on Nov 06, 2019 at 23:02 UTC ( [id://11108406]=note: print w/replies, xml ) Need Help??


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

Hi Anon

Here's another approach

#!perl -sl use strict; use warnings FATAL => 'all'; my $PATH = "c:/code/test"; my $processed_hash_ref; chdir $PATH; # filetests using relative path opendir DH, "." or die "Couldn't open directory $PATH: $!"; while ($_ = readdir (DH)) { next unless -f $_ && m/^\d_\d{4}_\d\d?_\d\d?_\d\d?_\d\d?_\d\d?_table/i; my $fname = join ('_', (split /_/)[ 7..11 ]); # already seen a more recent file with the name we're # planning to use? skip current file next if defined $processed_hash_ref->{$fname} && $processed_hash_ref->{$fname}->{AGE} < -M _; # file safe to be renamed... for now $processed_hash_ref->{$fname}->{OLDNAME} = $_; $processed_hash_ref->{$fname}->{AGE} = -M _; } closedir DH; # now proceed to rename items map { print "[!] rename $processed_hash_ref->{$_}->{OLDNAME} to $_"; rename $processed_hash_ref->{$_}->{OLDNAME}, $_; } keys %$processed_hash_ref;

Cheers
Shadow

  • Comment on Re: Batch file renaming - on identical name, keep only most recent file, based on dates
  • Download Code

Replies are listed 'Best First'.
Re^2: Batch file renaming - on identical name, keep only most recent file, based on dates
by haukex (Archbishop) on Nov 07, 2019 at 07:54 UTC
    -M _

    I think it's very much worth noting that this relies on the file's modification time being the same as the timestamp in the filename, which is IMHO is pretty risky. For example, if the timestamp in the filename is the time a log file was started, its modification time may very well be much later than that. Or, if the files were copied into this directory from somewhere else, the modification times may be completely unreliable.

      ++, but the timestamp in the original file name doesn't necessarily refer to creation/update of the corresponding file, either.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11108406]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (1)
As of 2024-04-25 00:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found