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:sqlReportsMycustomerIncoming
SET Loc2Dir=D:sqlReportsMycustomerPDF
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
6
@ECHO OFF
SETLOCAL
SET "Loc1Dir=U:sqlReportsMycustomerIncoming"
SET "Loc2Dir=U:sqlReportsMycustomerPDF"
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:
-
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 samecmd
instance. -
Use
set "var=value"
for setting string values – this avoids potential
problems caused by trailing spaces. -
Use required prefix in the filemask so that files
myprefix-*
only are detected. This eliminates the possibility of detecting a file namedNOTmyprefix-*
and changing that toNOTThisisnew_*
-
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 fromF
toE
-
Quoted parameters delivered to subroutine to avoid potential problems with spaces.
-
Syntax error –
GOTO: EOF
should beGOTO :EOF
-
Relevant
move
command constructed and echoed for verification. To activate once verified, removeecho
keyword. Append>nul
to suppress...file(s) copied
report. -
To view the report when using point-click-and-giggle methodology, insert the
PAUSE
line after thefor...
line
I seem to have this working now.
New to Batch scripting and did not realize :::lines were commented out.
I switched the bottom 2 lines and it seemed to work
REN "%copyfname%" "%fname%"
echo F | XCOPY /Y /F "%fname%" "%Loc2Dir%%fname%"
1