Batch file 如何将空格分隔的变量传递到bat文件中?
我想将一个空格分隔的变量传递到批处理文件中,如:Batch file 如何将空格分隔的变量传递到bat文件中?,batch-file,Batch File,我想将一个空格分隔的变量传递到批处理文件中,如: c:\applications\mi_pocess.bat A1 1AA 当我在mi\u进程中运行echo%1时,它返回A1 我将如何识别A1 1AA为单个字符串 我曾尝试在我的外部软件中使用双引号将其包装,如 c:\applications\mi_pocess.bat + chr$(34) + A1 1AA + Chr$(34) 和echo%1现在返回“A1 1AA”(我不希望变量中有引号) 感谢这是向批处理文件发送包含空格的值的唯一方法,
c:\applications\mi_pocess.bat A1 1AA
当我在mi\u进程中运行echo%1
时,它返回A1
我将如何识别A1 1AA
为单个字符串
我曾尝试在我的外部软件中使用双引号将其包装,如
c:\applications\mi_pocess.bat + chr$(34) + A1 1AA + Chr$(34)
和echo%1
现在返回“A1 1AA”
(我不希望变量中有引号)
感谢这是向批处理文件发送包含空格的值的唯一方法,因此如果您不需要引号,则必须在批处理文件中删除它们。我相信您知道,%1
、%2
等。bat中的参数表示在命令行上传递给.bat的编号参数
如果将它们用作%~1
,%~2
等。如果它们在那里,所有周围的引号将自动删除
考虑args.bat中的空格进行测试:
@echo off
echo. %1
echo. (original first argument echo'd)
echo.
echo. "%1"
echo. (original first argument with additional surrounding quotes)
echo.
echo. %~1
echo. (use %%~1 instead of %%1 to remove surrounding quotes, should there be)
echo.
echo. "%~1"
echo. (we better use "%%~1" instead of "%%1" in this case:
echo. 1. ensure, that argument is quoted when used inside the batch;
echo. 2. avoid quote doubling should the user have already passed quotes.
echo.
运行它:
space-in-args.bat "a b c d e"
输出为:
"a b c d e"
(original first argument echo'd)
""a b c d e""
(original first argument with additional surrounding quotes)
a b c d e
(using %~1 instead of %1 removes surrounding quotes, should there be some)
"a b c d e"
(we better use "%~1" instead of "%1" in this case:
1. ensure, that argument is quoted when used inside the batch;
2. avoid quote doubling should the user have already passed quotes.
另请参见获取/?
(向下滚动到末尾)以了解更多的转换。您可以在批处理文件中使用%~1
:
echo %1
echo %~1
收益率:
> test "A1 AA1"
"A1 AA1"
A1 AA1
因为%~1
从参数中删除引号
另一个选项是%*
,如果您只需要一个参数<代码>%*
包含批处理文件的所有参数。这将使您能够避免在此处使用引号,但也意味着如果您想给出另一个不应属于您当前期望的论点,您就太倒霉了:
echo %*
然后产生:
> test2 A1 AA1
A1 AA1
您应该使用%*来获取除%0之外的所有参数
如果用这种方式调用某个批处理文件
呼叫一些bat 54 12 33
带代码
set params=%*
echo Params goted : %params%
它将返回:
Params goted : 54 12 33
谢谢皮皮塔斯,这解释得很好,谢谢约翰。现在在我的处理过程中实现了类似的功能。你已经感谢了两个人,他们回答了你的问题吗?如果是这样的话,接受这个答案。