Filtering arguments in windows batch file
Is it possible to filter list of arguments in windows batch file?
Assuming it is called like:
file.cmd arg1 --unwanted arg3
It should call some other executable (hardcoded) without the argument string --unwanted
:
some.exe arg1 arg3
I only know the name of the argument, it can be passed as any argument in the list. It may not exist on argument list, and the all arguments should be passed unmodified. Number of arguments may vary.
More examples (what's called -> what should be called in result)
file.cmd arg1 arg2 -> some.exe arg1 arg2
file.cmd --unwanted -> some.exe
fil开发者_StackOverflowe.cmd --unwanted arg2 -> some.exe arg2
file.cmd arg1 --unwanted -> some.exe arg1
Moving from unix shell scripting windows batch files are black magic to me :)
@echo off
setlocal ENABLEEXTENSIONS
if "%1"=="SOTEST" (
REM tests...
call file.cmd arg1 --unwanted arg3
call file.cmd arg1 arg2
call file.cmd --unwanted
call file.cmd --unwanted arg2
call file.cmd arg1 --unwanted
goto :EOF
)
set params=
:nextparam
if "%~1"=="--unwanted" (shift&goto nextparam)
if not "%~1"=="" (set "params=%params%%1 "&shift&goto nextparam)
echo.%*^>^>%params%
This prints:
arg1 --unwanted arg3>>arg1 arg3
arg1 arg2>>arg1 arg2
--unwanted>>
--unwanted arg2>>arg2
arg1 --unwanted>>arg1
Edit:
@echo off
setlocal ENABLEEXTENSIONS
if "%~1"=="SOTEST" (
REM tests...
call file.cmd arg1=foo --unwanted arg3=bar
call file.cmd arg1 arg2
call file.cmd --unwanted
call file.cmd --unwanted arg2
call file.cmd arg1 --unwanted
call file.cmd "arg1" --unwanted "arg3"
call file.cmd "arg1=foo" --unwanted arg3="bar"
goto :EOF
)
set var=0
set params=
:nextparam
set /A var=%var% + 1
for /F "tokens=%var% delims= " %%A in ("%*") do (
if not "%%~A"=="--unwanted" set "params=%params%%%A "
goto nextparam
)
echo.%*^>^>%params%
prints
arg1=foo --unwanted arg3=bar>>arg1=foo arg3=bar
arg1 arg2>>arg1 arg2
--unwanted>>
--unwanted arg2>>arg2
arg1 --unwanted>>arg1
"arg1" --unwanted "arg3">>"arg1" "arg3"
"arg1=foo" --unwanted arg3="bar">>"arg1 foo" arg3="bar"
meaning "arg1=foo" is broken, you can switch the for loop to for /F "tokens=%var% delims= " %%A in ('echo.%*') do (
to get it working, but that breaks arg1=foo and arg3="bar"
This is a known problem with batch files, once you start messing with strings things are going to get screwed up in some configuration since there is always some character that is going to mess things up (%,!,",^,&,|,<,>,space etc)
精彩评论