how to apply substring command to double percent variable in XP cmd scripts?

有些话、适合烂在心里 提交于 2020-01-03 14:19:12

问题


here is the example how you do it with normal variables:

SET _test=123456789abcdef0
SET _result=%_test:~-7%
ECHO %_result%
:: that shows: abcdef0

But what to do with variables with double percent at the begin (like %%A), variables like this are needed in for loops:

FOR /D %%d IN (c:\windows\*) DO (
  echo %%d
)

this works, but:

FOR /D %%d IN (c:\windows\*) DO (
  echo %%d:~-7%
)

simply copies :~-7 into the echo command


回答1:


The replace and substring syntax only works for variables not for parameters.

But you can simply copy the parameter into a variable and then use the substring syntax.

setlocal EnableDelayedExpansion
FOR /D %%d IN (c:\windows\*) DO (
  set "var=%%d"
  echo !var:~-7!
)

You need here the delayed expansion, as a normal %var% would be expanded while parsing the complete block, not at execution time.

Or you could use the call technic, but this is very slow and have many side effects.

FOR /D %%d IN (c:\windows\*) DO (
  set "var=%%d"
  call echo %%var:~-7%%
)


来源:https://stackoverflow.com/questions/8281242/how-to-apply-substring-command-to-double-percent-variable-in-xp-cmd-scripts

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