检查批处理脚本中的字符串是否为空/只有空格

时间:2019-08-26 09:34:07

标签: batch-file

请参见以下代码 示例:

任何人都可以提供解决方案吗?

我有一个批处理脚本,该脚本中的变量很少包含字符串和数字之类的值。有时,我得到一个空字符串或仅包含空格的字符串作为输入。我想部署条件以过滤掉这些情况。

 set Test_String = "   "

if Test_String=="empty/contains only spaces" 
//(do nothing )
else
//(do something)

我想获得将其部署到.bat文件中的解决方案

2 个答案:

答案 0 :(得分:3)

具有查找/替换功能的Compo IF解决方案可能是最简单,性能最好的方法。

但是,如果需要解析值,则FOR / F可能是一个很好的解决方案。例如,默认的空间delims将有效地修剪前导和尾随空格。

FOR /F如果字符串为空或仅包含空格/制表符,则不会迭代该字符串。 EOL选项应设置为空格,以免错误地漏掉以;开头的行(感谢Stephan的评论)。因此,如果您想做一些非空的操作,而在空(或空白)时什么也不做,那么

for /f "eol= " %%A in ("%VAR%") do (
  echo VAR is defined and contains more than just spaces or tabs
)

如果要对空(或空格值)采取措施,则可以利用以下事实:FOR / F如果不进行迭代,则返回非零值。您必须将整个FOR构造包含在括号中,以正确检测空条件。并且应确保DO子句的最后一条命令始终返回0。

(
  for /f "eol= " %%A in ("%VAR%") do (
    echo VAR is defined and contains more than just spaces or tabs
    rem Any number of commands here
    (call ) %= A quick way to force a return code of 0. The space after call is critical =%
  )
) || (
  echo VAR is not defined or contains only spaces/tabs
)

答案 1 :(得分:2)

您需要学习的第一件事是如何使用首选/推荐语法设置变量。 Set "Test_String= "将变量Test_String定义为单个空格的值,而set Test_String = " "将变量%Test_String %定义为 " "的变量。

您可以执行字符替换,不使用空格替换空格字符,然后您的验证将针对未定义/空字符串:

@Set /P "Test_String=Please enter a string here to test against:"
@If "%Test_String: =%" == "" (Echo empty/contains only spaces) Else Echo do something
@Pause


变量不能没有值,可以是一个值,也可以是未定义的值,因此,如果您想知道最终用户是否在输入提示时输入了条目,则可以这样操作:

@Set "Test_String="
@Set /P "Test_String=Please enter a string here to test against:"
@If Not Defined Test_String (Echo no entry was made) Else Echo an entry was made
@Pause