how to apply substring command to double percent v

2019-06-28 05:35发布

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条回答
太酷不给撩
2楼-- · 2019-06-28 06:03

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

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%%
)
查看更多
登录 后发表回答