I refer to question Add text to end of filename (but before extension) using batch file as I have the same problem. Using Windows 7 32-bit Enterprise (I know, I know …) with all updates I wrote a tiny batch file pdfrename.bat
with only three lines:
-
a comment, starting with
REM
and no "hidden" continuation sign more to the right of the line -
the proposed command, copy-pasted from the source as provided by @Karan, commented out with
REM
-
the adopted command for batch (doubling the
%
):REM Rework 2020-12-16 REM for %a in (*.txt) do ren "%~a" "%~na version 1%~xa" for %%F in (*.pdf) do ren "%%~F" "%%~nF OdB%%~xF"
Running the command (3.) from the command-prompt,
for %F in (*.pdf) do ren "%~F" "%~nF OdB%~xF"
works fine.
But executing the whole batch-file pdfrename.bat
from Windows explorer fails. Running the batch file from the command prompt pdfrename.bat
produces an error message syntax error:
Die folgende Verwendung des Pfadoperators zur Ersetzung eines Batchparameters
ist ungültig: %~na version 1%~xa"
[...]
You need not to understand German. The important point is that the error message refers to the commented out second line (2.), not to the third line!
I tried to retype REM
, inserted a tabulator after REM, inserted a second REM
after the first (REM REM ....
), inserted a third line after the second one with the same content and deleted the second line afterwards – nothing changed: the batch file terminates at the commented out second line with a syntax error. As soon as the incriminated second line is eliminated from the batch, the batch works fine.
I searched for "REM is ignored", but no luck, so I post the matter here. I never heard about or experienced before that the command processor tries at least to analyze a commented out line – and in the case that there is something wrong with the code after the comment-sign that it terminates the batch script.
Best Answer
The error-msg refers to the commented out second line
This is due to the very complex parsing that is used by
cmd
to process scripts.In short the parser processes
%
before pretty much everything else (phase 1) and throws an error as some of the%
s need to be doubled as%%
when used in a batch file.So in a batch file:
is a valid command and:
is a broken command (the
%a
should be%%a
, etc).Note that:
is a valid command when run from the command line as then the
%
does not need to be doubled.REM
would be processed in phase 2 of the parser, but it never gets there as the%
processing in phase 1 has already generated an error and terminated the parsing.For all the gory details of the
cmd
parser please read parsing - How does the Windows Command Interpreter (CMD.EXE) parse scripts? - Stack Overflow