Search code examples
windowsfor-loopbatch-renameexiftool

Windows batch add suffixes to filenames with EXIF values in current folder with FOR loop


I'm trying to get some EXIF data added to the filenames in a folder. So far, I've been able to get the smaller pieces to work, but I can't get the name and extension separated so the can be combined with the EXIF values via the FOR loop.

I saw that I need to use ! to delineate the variable in the loop, but I can't get this to work with the filename.

SETLOCAL ENABLEDELAYEDEXPANSION
for /f "tokens=* delims=" %%a in ('dir /b *') do (
    set file=%%~a
    set _fname=%~n1
    set _ext=%~x1
    for /f %%i in ('exiftool.exe -s -S -SourceImageWidth %file%') do set WIDTH=%%i
    for /f %%i in ('exiftool.exe -s -S -SourceImageHeight %file%') do set HEIGHT=%%i
    for /f %%i in ('exiftool.exe -s -S -CompressorID %file%') do set CODEC=%%i
    rename %file% "%_fname% [%WIDTH%x%HEIGHT% %CODEC%]%_ext%"
)

The process is: get filename -> get name only -> get extension -> get EXIF values -> rename file with values added to name and reuse extension -> repeat on next file in current directory

I apologize for the sloppy batch syntax as I'm sure there's a much more optimal way of coding.

Thank you!


Solution

  • You are making Exiftool Common Mistake #3. Exiftool's biggest performance hit is its startup time and using it in a loop like this will take a significantly longer time, especially since exiftool has very powerful batch and renaming abilities on its own.

    Try this as a single command
    exiftool "-Filename<%f [${SourceImageWidth}x$SourceImageHeight $CompressorID].%e" /path/to/files

    Add -r to recurse into subdirectories. Remember to double any percent signs if used in a .BAT file.

    The %f token stands for the base filename without the extention. The tags names are inserted by adding a dollar sign in front of them. Because SourceImageWidth is directly adjacent to the x, braces are used to separate the two so exiftool doesn't go looking for a tag named "SourceImageWidthx". The %e stands for the file extension.