使用批处理变量中的字符串修剪字符串

时间:2012-07-26 13:14:42

标签: batch-file trim

如果你的参数无效,我有一个批次显示用法。

对于前。

   Running "sample.bat update fuh"

   :usageactions
   set actions=%*
   set toremove=update
   set todisplay=%actions:%toremove% =%
   echo Error: Invalid Arguments - '%todisplay%'.
   echo Type sample.bat %toremove% -h for usage.

预期产出:

  Error: Invalid Arguments - 'fuh'.
  Type sample.bat update -h for usage

但我的输出是:

  Error: Invalid Arguments - 'update'.
  Type sample.bat update -h for usage

如何实现它?任何帮助,将不胜感激。感谢。

(顺便说一下,如果问题太混乱,请修改问题。)

2 个答案:

答案 0 :(得分:3)

您尝试在一行中多次展开表达式,但解析器无法猜测哪些百分比是对。

set todisplay=%actions:%toremove% =%

你可以在这里使用延迟扩展

setlocal EnableDelayedExpansion
set toDisplay=!actions:%toRemove% =!

首先%%toRemove%将被展开,然后该行看起来像

set toDisplay=!actions:update =!

然后将评估感叹号表达式。

答案 1 :(得分:0)

幸运的是,我找到了解决问题的方法,呵呵。无论如何,这是解决方案。

:usageactions
setLocal EnableDelayedExpansion
set actions=%*
set toremove=update
set todisplay=!actions:%toremove% =!
echo Error: Invalid Arguments - '%todisplay%'.
echo Type sample.bat %toremove% -h for usage.
endlocal

将显示。

Error: Invalid Arguments - 'fuh'.
Type sample.bat update -h for usage