Search code examples
batch-filecommand-linecommand-promptbatch-rename

Rename Multiple Files in a folder using batch script


I have a folder called TEST. Inside there are 30 files.

Example:

DIM1_UPI_20170102.TXT

DIM2_UPI_20170908.TXT

DIM3_UPI_20180101.TXT

...

I have to rename them by removing the date tag Exapmple:

DIM1_UPI.TXT

DIM2_UPI.TXT

DIM3_UPI.TXT

Can you please help me writing this in batch file?


Solution

  • Assuming your files are all starting with DIM

    @echo off
    setlocal enabledelayedexpansion
    for /f %%i in ('dir "*.TXT" /b /a-d') do (
     set "var=%%~ni"
     echo ren !var!%%~xi !var:~0,-9!%%~xi
    )
    

    Once you can confirm that it does what you want, and ONLY then, remove the echofrom the last line to actually rename the files.

    Important Note. If you have files with similar names, but different date entries, this will not work as you think. as Example:

    DIM2_UPI_20170910.TXT

    DIM2_UPI_20170908.TXT

    The names are the same, but dates differ, making each filename Unique. If you rename them, there can be only 1 DIM2_UPI.TXT So as long as you understand this, you will be fine.

    Edit: based on Amazon drive question. Note you need to change the directory portion to how you access amazon drive.

    @echo off
    setlocal enabledelayedexpansion
    for /f %%i in ('dir "DIM*" /b /a-d') do (
     set "var=%%~ni"
     echo ren !var!%%~xi !var:~0,-16!%%~xi
    )