How to strip quotes from the script arguments in batch files?

混江龙づ霸主 提交于 2019-12-10 18:37:00

问题


Suppose you're writing a Batch script in which you want to strip the quotes from a string.

If the string is stored in a regular Batch variable, you would do this:

set name="John"
echo %name:"=%

If the string is stored in a positional parameter, you would do this:

echo %~1

How would you go about achieving the same effect for script arguments, specifically the %* variable? When I try to use the same notation I use for positional paramters, I get this:

> echo echo %~* > script.cmd

> script "123" "456"
The following usage of the path operator in batch-parameter
substitution is invalid: %~* 


For valid formats type CALL /? or FOR /?
script was unexpected at this time.

How can I make this work? Is there any special syntax for this that I'm not aware of? Any help would be appreciated, thanks!


回答1:


Suppose you're writing a Batch script in which you want to strip the quotes from a string.

If the string is stored in a regular Batch variable, you would do this:

set name="John"
echo %name:"=%

Your assertion is incorrect. A better convention when working with string values is always to set "variable=value" with the "variable=value" pair quoted, then add quotation marks explicitly when needed upon retrieval, rather than upon assignment. For example:

@echo off
setlocal

set "xml=<node>Text</node>"
for /f "tokens=2 delims=<>" %%I in ("%xml%") do echo Text: %%I

And thus, the quotation marks are not included in the variable value, but whatever special characters are quoted avoid being interpreted inappropriately. Even though this isn't really what you're asking, it's still a fundamental convention that's worth practicing.


If the string is stored in a positional parameter, you would do this:

echo %~1

How would you go about achieving the same effect for script arguments, specifically the %* variable?

True, you can use tilde notation for individual arguments with a numeric index, but not for the %* collection. To solve your riddle, you'd have to iterate through %* either with a for...in or shift...goto loop. for...in is the more efficient choice. Here's one of a hundred possible paths to a working solution.

@echo off
setlocal enabledelayedexpansion

set "argv[0]=%~0"
set idx=1

for %%I in (%*) do (
    set "argv[!idx!]=%%~I"
    set /a ubound = idx, idx += 1
)

for /L %%I in (0,1,%ubound%) do echo %%I: !argv[%%I]!

rem // or you could also:
rem // set argv[


来源:https://stackoverflow.com/questions/36121630/how-to-strip-quotes-from-the-script-arguments-in-batch-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!