Search code examples
batch-filecmd

Batch Rename and Move Files with CMD


I wonder if someone can help me with running some code as a batch file with CMD. I have a list of files in a directory, that i wish to replace the filename e.g. "Myprefix-" with "Thisisnew_" and move the files to a new location.

File names are currently like MyPrefix-INVOICE1_C.PDF I would like them replaced with Thisisnew_INVOICE_C.PDF Then move them into another directory (not copy)

I have found this script, but even when I add pause to the end, I cant see what the issue is as it does not run.

@ECHO ON

SET Loc1Dir=D:\sql\Reports\Mycustomer\Incoming
SET Loc2Dir=D:\sql\Reports\Mycustomer\PDF

CD /D "%Loc1Dir%" 
FOR /R %%F IN ("*-*.PDF") DO CALL :copyFile %%~F %%~NXF
GOTO: EOF 

:copyFile
SET copyfname=%~1
SET fname=%~2 
SET fname=%fname:MyPrefix-=Thisisnew_% 
ECHO F | XCOPY /Y /F "%copyfname%" "%Loc2Dir%\%fname%"
:::XCOPY /Y /F "%copyfname%" "%Loc2Dir%\"
:::REN "%copyfname%" "%fname%"
GOTO :EOF

Solution

  • @ECHO OFF
    SETLOCAL
    
    SET "Loc1Dir=U:\sql\Reports\Mycustomer\Incoming"
    SET "Loc2Dir=U:\sql\Reports\Mycustomer\PDF"
    
    CD /D "%Loc1Dir%" 
    FOR /R %%E IN ("myprefix-*.PDF") DO CALL :copyFile "%%~E" "%%~NXE"
    GOTO :EOF 
    
    :copyFile
    SET "fname=%~2"
    SET "fname=%fname:MyPrefix-=Thisisnew_%" 
    ECHO MOVE "%~1" "%Loc2Dir%\%fname%" 
    GOTO :EOF
    

    Note:

    I use U: for testing, so any drive references have been changed.

    Changes:

    1. Insert setlocal. This ensures that changes made to the environment from running one batch does not pollute the environment for the next batch run in the same cmd instance.

    2. Use set "var=value" for setting string values - this avoids potential problems caused by trailing spaces.

    3. Use required prefix in the filemask so that files myprefix-* only are detected. This eliminates the possibility of detecting a file named NOTmyprefix-* and changing that to NOTThisisnew_*

    4. I prefer to avoid ADFNPSTXZ (in either case) as metavariables (loop-control variables) as ADFNPSTXZ are also metavariable-modifiers which can lead to difficult-to-find bugs (See for/f from the prompt for documentation) - metavariable changed from F to E

    5. Quoted parameters delivered to subroutine to avoid potential problems with spaces.

    6. Syntax error - GOTO: EOF should be GOTO :EOF

    7. Relevant move command constructed and echoed for verification. To activate once verified, remove echo keyword. Append >nul to suppress ...file(s) copied report.

    8. To view the report when using point-click-and-giggle methodology, insert the PAUSE line after the for... line