Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 232
rsk82 Avatar asked Nov 26 '11 19:11

rsk82


People also ask

What does %% mean in CMD?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

What is %% f in batch script?

By default, /F breaks up the command output at each blank space, and any blank lines are skipped.

How do I echo a variable in CMD?

To reference a variable in Windows, use %varname% (with prefix and suffix of '%' ). For example, you can use the echo command to print the value of a variable in the form " echo %varname% ".


1 Answers

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%%
)
like image 89
jeb Avatar answered Nov 15 '22 05:11

jeb