Assuming this command line is in variable input
:
This works on the command line, to test the approach:
for /f delims^=^"^ tokens^=1 %a in ('echo %input:*-h =%') do @echo %a
And this is your code for a batch file (reading from %input%
and saving into %result%
):
for /f delims^=^"^ tokens^=1 %%a in ('echo %input:*-h =%') do @set result=%%a
echo %result%
This works by first cutting everything until the -h
in a variable string replacement expression and then using for /f
with the "
as delimiter. In order to be able to specify the "
as delimiter, we can't enclose the delims=... tokens=...
part in quotes as we'd normally do, instead we have to escape every individual character with special meaning (including the space) with ^
.
Note: This assumes that the path will always be quoted in the command line. If it isn't, you'd need to first check if the part after cutting the left side starts with a quote and then either use the quote or the space as delimiter accordingly:
set x=%input:*-h =%
if ^%x:~0,1% equ ^" (
for /f delims^=^"^ tokens^=1 %%a in ('echo %x%') do @set result=%%a
) else (
for /f tokens^=1 %%a in ('echo %x%') do @set result=%%a
)
echo %result%
...but having to resort to this sort of unreadable trickery seriously makes me wonder whether it even makes sense to use batch files with decades of legacy for this. Did you consider using PowerShell or Python or some other proper scripting language instead?