1
votes

I am trying to create a batch script to rename downloaded files. After downloading, the files have similar names that include a timestamp. The timestamps in the name differ from the value of the "last modified" timestamp (typically by only a few seconds). For example:

Export_2013_11_06_15_13_31.csv
Export_2013_11_06_15_13_41.csv
Export_2013_11_06_15_13_51.csv

etc.

Each of these files needs to be renamed to a SPECIFIC name in alphabetical order according to their last modified timestamp (not the timestamp in the name). The most recent file must be named Bart.csv, the next Carol.csv, and the oldest June.csv.

Is there a way to ensure the files are renamed in the correct order?

1
If the actual file time stamps have these differences as well, check out the dir /o flag and options. Something like dir /a-d /b /o-dDavid Ruhmann
@DavidRuhmann How would I use that in the batch file? I'm not sure of what the line you posted is doingCass
To see the documentation for the dir command type dir /? on the command line. The line I posted will list only files /a-d (no directories), remove formatting /b, and sort the files in descending date order /o-d (newest first). This can then be combined with a for /f loop and the ren command.David Ruhmann

1 Answers

4
votes
@echo off&setlocal
set "name1=Bart"
set "name2=Carol"
for /f "delims=" %%a in ('dir /b /a-d /o-d') do (
    set "fname=%%~a"
    set /a counter+=1
    SETLOCAL ENABLEDELAYEDEXPANSION
    call set "nname=%%name!counter!%%"
    echo ren "!fname!" "!nname!%%~xa"
    endlocal
)

Remove echo to get it working.