检查逗号分隔列表是否为空(空白)时出错

时间:2017-07-13 05:24:32

标签: arrays batch-file string-comparison

我得到一个逗号分隔列表,其中包含数据库中字段的值。此列表有时为空白。我需要检查列表是否为空,然后执行某些操作。如果列表不为空,则采取其他操作。

问题是我在检查列表是否为空时收到错误。这是代码。请注意,我在代码的开头模拟了值来自数据库。

以下是我之前尝试的内容:如果VendorStores列表为空(空白),请执行一项操作。否则采取另一个行动。当VendorStores具有多个值(逗号分隔)并且将其与空白进行比较时,我收到错误。所以现在我正在尝试计算值并使用该计数来做出决定。但是我遇到了同样的问题。当VendorStores为空时,for循环仍认为它有2个值 - 1)",=" 2)""。不知道为什么会这样。

:: Intention of the script is as follows:
:: If VendorStores list is blank, take one action
:: If VendorStores list has values, take another action

@echo off
:: Set values for VendorStores
:: set vendorstores=123,234,345
:: Set VendorStores to blank
set vendorstores=
echo list = "%vendorstores%"
:: Remove any blank spaces from VendorStores
set vendorstores=%vendorstores: =%
set /a c=0
echo c=%c%
SETLOCAL EnableDelayedExpansion
for %%a in ("%vendorstores:,=" "%") do (
    if [%%a] NEQ [] (
        set /a c=c + 1
        echo VendorStore is %%a
    )
    echo c=!c!
)
echo c=!c!
if [!c!] EQU [0] (
    echo c is equal to Zero
) else (
    echo c is greater than Zero
)
echo c=!c!
endlocal

3 个答案:

答案 0 :(得分:0)

错误的结果来自 FOR 命令行:

echo on

在此命令行上方插入一行@echo off,在 FOR 右括号后加for %%a in (%vendorstores%) do ( 一行,可以很容易地看出它失败的原因。

正确的命令行是:

vendorstores

但是,如果没有定义环境变量Test.bat,则使用此 FOR 循环并不好。

以下是名为@echo off set "VendorStores=%~1" if not defined VendorStores goto EmptyList set "VendorStores=%VendorStores: =%" if not defined VendorStores goto EmptyList if "%VendorStores:,=%" == "" goto EmptyList echo List is: %VendorStores% goto :EOF :EmptyList echo The list is empty. 的批处理文件的简化示例:

Test.bat
Test.bat ,,,,
Test.bat ", , , ,"
Test.bat " 123, 234, 345 "
Test.bat "376,983,305,253"

此批处理文件可以在命令提示符窗口中执行,如下所示:

{{1}}

这5个批处理文件执行的输出是预期输出的5倍。

答案 1 :(得分:0)

:: Intention of the script is as follows:
:: If VendorStores list is blank, take one action
:: If VendorStores list has values, take another action

@echo off
:: Set values for VendorStores
:: set vendorstores=123,234,345
:: Set VendorStores to blank
set vendorstores=
echo list = "%vendorstores%"
:: Remove any blank spaces from VendorStores
set vendorstores=%vendorstores: =%

::::If there is any value in StoreCSV, then remove any comma delimiters from it as the "if" statement does not like commas
if defined vendorstores (
set "vendorstores=%vendorstores:,=%"
)

SETLOCAL EnableDelayedExpansion

if [%vendorstores%] EQU [] (
    echo VendorStores is blank
) else (
    echo VendorStores has one or more values
)

endlocal

答案 2 :(得分:0)

这是另一种选择:

@Echo Off
Set "VendorStores="
For /F "EOL=, Delims=, " %%A In ("%~1") Do Set "VendorStores=%%A"
If Not Defined VendorStores (Echo VendorStores is blank
) Else Echo VendorStores has one or more values