Search code examples
windowsbatch-filebatch-rename

Batch file to read file names from CSV and rename files in a folder


I have a set of codes in a file, i want to rename the files in a folder with that code. Like first code for the first file then second code for the second file.

for /f "delims=" %%x in (code.csv) do call :rename "%%x" 
pause
GOTO :EOF

:rename
REN "*.jpg" "a/%1.jpg"

This is what I have written but this is like running the first code for all the files and am getting a duplicate file name that exists or the file can not found error. Even though the files are being renames but it takes lots of time which I believe due to some unnecessary looping.

Any help to make it perfect will be appritiated


Solution

  • You need a way to read the directory and the csv in parallel. There is a trick to do that:

    @ECHO OFF
    setlocal enabledelayedexpansion
    <code.csv (
      for /f "delims=" %%x in ('dir /b *.jpg') do (
        set "NewName="
        set /p NewName=
        if not defined NewName goto :eof
        ECHO ren "%%x" "!NewName!"
      )
    )
    

    NOTE: remove the ECHO command after verifying it does what you want to actually enable the ren command.

    <code.csv ( ... ) provides one line after the other to the set /p within the for loop. Clear it before reading, so the NewName variable gets undefined, when there are no more names from the csv. Exit the for loop, when it is undefined (no more names).

    The loop stops, when there are either no more files to be renamed or no more new names from the csv file.

    See dir /? - especially the /o switch for how to sort the files (if needed) for names, dates or sizes.

    Another possibility is to build an array of either the csv content or the files but I think that's an overkill for this task.