Thomas
Thomas

Reputation: 77

Batch File - Set

I want to get dir=%dir:~-here% a var.

I find out that this dir=%dir:~-%var%% unfortunaly this doesn`t work. then I tried :

set var=2

echo dir=%%dir:~-%var%%% > file.txt

for /f "tokens=* delims=" %%a in (file.txt) do set dir=%%a

but then is dir for real %dir:~-2%. If anybody understands my, am I asking you is there a way to do it?? THNX

Upvotes: 0

Views: 89

Answers (3)

MC ND
MC ND

Reputation: 70923

@echo off

    setlocal enabledelayedexpansion
    set "var=-2"

    echo !cd:~%var%!

To use a variable inside a variable substring operation, the easiest way is to use delayed expansion

Upvotes: 3

foxidrive
foxidrive

Reputation: 41224

Here is another way to do it with your example.

Using call this way causes an issue with ^ characters and is relatively slower than delayed expansion.

@echo off
set dir=aaabbbccc
set var=3
>file.txt call echo dir=%%dir:~-%var%%% 
pause

Upvotes: 0

Aacini
Aacini

Reputation: 67196

If you want to expand variables in a line two times, you need to use Delayed Expansion:

setlocal EnableDelayedExpansion
set var=2
echo dir=!dir:~-%var%! > file.txt

The first expansion happen at %var%, the second (delayed) expansion happen at !dir:~-2!.

EDIT: Another possible way is use the call command that causes that the line be parsed again:

set var=2
call echo dir=%%dir:~-%var%%% > file.txt

When the line is parsed the first time, the first expansion is performed:

call echo dir=%dir:~-2% > file.txt

The call command causes that the line be parsed again and get the final result.

Upvotes: 2

Related Questions