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

Ok, so I brought it here: I first get all the filenames into one text file and then I run the following, on the file:
use strict; use warnings; use Date::Parse; my @AoA_files=(); open IN, $ARGV[0]; while(<IN>) { my $infile=$_; chomp $infile; if($infile=~/^(\d+)\_(\d+)_(\d+)_(\d+)_(\d+)_(\d+)_(\d+)_(.*)/) { my $uid=$1; my $year=$2; my $month=$3; my $day=$4; my $hour=$5; my $minute=$6; my $second=$7; my $actual_filename=$8; my $timestamp = "$year-$month-$day"."T"."$hour:$minute:$second +"; if ( grep { $_->[1] eq $actual_filename } @AoA_files ) #if fil +ename exists, keep only the most recent one { #compare the timestamps my $existing_timestamp = $_->[0]; my $difference_in_seconds = str2time($timestamp) - str2tim +e($existing_timestamp); if($difference_in_seconds > 0) #current date is newer than + the one in the AoA - use this one { push @AoA_files, [ $timestamp, $actual_filename]; } } else #add it normally to the AoA { push @AoA_files, [ $timestamp, $actual_filename]; } } }
My idea here is to eventually create a second file with the full filenames that I need to keep. Does that make sense?
  • 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 Fletch (Bishop) on Nov 05, 2019 at 14:33 UTC
    • ALWAYS check the return value from open and show the error: open( ... ) or die qq{Problem opening '$ARGV[0]': $!\n};
    • If you'd use a hash like I suggested rather than an AoA it'd be more efficient; you're doing a linear search over all of your filenames repeatedly whereas a hash can just do exists

    Those nitpicks aside, seeing as that's basically my suggestion above . . . looks sane. (Sanity not guaranteed. Contents may have settled during shipping. Prices may be higher in AK and HI.)

    Edit: tweaked wording of second item slightly. Me no make sense much early morning do.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.