Search code examples
batch-filebatch-rename

batch file to rename files also tries to rename directories


The following batch file works to take directory and file names from a txt file and rename the files in the directory according to the names given.

SETLOCAL EnableDelayedExpansion

(for /f "tokens=1,2 delims=;" %%A in ('"TYPE C:\RENAME-ALL.txt"') do (
echo %%A | find /i "\" 
 if !errorlevel! equ 1 (
RENAME "D:\!mypath!%%A" "%%B" 
 ) ELSE (
echo "found pattern"
echo %%A
set  mypath=%%A
  echo mypath is !mypath!
 )
)
) >> C:\RENAME-ALL-4.txt 2>&1
endlocal

========== RENAME-ALL.TXT ================

mydirectory\photos\2019\  <= this is the directory
IMG_20190729_064619.jpg;IMG_20190825_064619.jpg   <=former name is replaced by the latter name

In this case, the batch file renames the file IMG_20190729_064619.jpg in the mydirectory\photos\2019 to IMG_20190825_064619.jpg.

However, the batch file also tries to rename mydirectory\photos\2019 to "" (This should not happen.) Can this be suppressed? How?


Solution

  • SETLOCAL EnableDelayedExpansion
    
    (for /f "tokens=1,2 delims=;" %%A in ('"TYPE C:\RENAME-ALL.txt"') do if "%%B"=="" (
      echo "found pattern"
      echo %%A
      set  "mypath=%%A"
      echo mypath is !mypath!
     ) ELSE (
      RENAME "D:\!mypath!%%A" "%%B" 
     )
    ) >> C:\RENAME-ALL-4.txt 2>&1
    endlocal