1

I have the following code:

set name=James
echo %name:~0,4%

And it displays the first 4 letters of the variable: Jame.
But I'd like to insert a variable for the number of letters displayed which I can change with set. Something like this:

set num=3
set name=James
echo %name:~0,%num%%

The result should be showing the first num characters of string value of variable name.

Is there any method to get desired result?

Mofi
  • 46,139
  • 17
  • 80
  • 143
  • 3
    Read about [delayedexpansion](https://ss64.com/nt/delayedexpansion.html) `call echo %%name:~0,%num%%%` –  May 19 '18 at 23:37
  • 1
    Take a look on all answers posted on [How to substitute variable contents in a Windows batch file?](https://stackoverflow.com/questions/4367297/) – Mofi May 20 '18 at 07:26
  • Take a look at this answer: [How to expand two local variables inside a for loop in a batch file](https://stackoverflow.com/a/41122788). – aschipfl May 20 '18 at 14:20

1 Answers1

1

You can either add a layer of % around the echo statement and call echo it.

@echo off
set num=3
set name=James
call echo %%name:~0,%num%%%

or you can simply enabledelayedexpansion

@echo off
setlocal enabledelayedexpansion
set num=3
set name=James
echo !name:~0,%num%!

For more help on delayedexpansion just run setlocal /? from cmdline.

Gerhard
  • 22,678
  • 7
  • 27
  • 43