Expanding arbitrary variable to a drive, path etc. in a DOS batch
-
19-09-2019 - |
Question
I am using a dos batch which processes file using passed parameter:
process.bat "D:\PROJECT\TEST FILES\test.pdf" 72
process.bat:
gswin32c -r%2 -sDEVICE=jpeg -sOutputFile="%~n1-%%d.jpg" -- "%~1"
We can see that the parameter is expanded to the file name in the batch: %~n1
.
However I was asked to rewrite the batch to read parameters from a text file:
params.txt
1 D:\PROJECT\TEST FILES\test.pdf
2 72
So I have modified the process.bat:
for /f "tokens=1,*" %%A in ('type ..\params.txt') do set P%%A=%%B
gswin32c -r%P1% -sDEVICE=jpeg -sOutputFile="%~nP2%-%%d.jpg" -- "%~1"
But %~nP2% doesn't work.
I have found that for /f "tokens=*" %%A in (%P1%) do %%~dA
could help me but it looks cumbersome.
So is there any other way to expand arbitrary variable to a name, drive, path etc.?
Solution
Yeah, those only work with the special number-based arguments. But you can turn your variable into one by passing it to a subroutine in the batch file. Example:
@echo off
set P1=D:\PROJECT\TEST FILES\test.pdf
call :Split %P1%
echo %FNAME%
exit /b 0
:Split
set FNAME=%~n1
exit /b 0
...prints "TEST" (the name part of test.pdf)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow