Is it possible to use variables in a substring operation?

Microsoft Windows
Post Reply
Rekrul
Posts: 52
Joined: 2021-Aug-15, 11:29 pm

Is it possible to use variables in a substring operation?

Post by Rekrul »

I want to do something like this;

Code: Select all

set String=1234567890
set /p x=Number of desired characters?
echo %String:~0,%x%%
Where the substring operation would return however many characters the user enters. If they enter "5", they'd get "12345".

I've tried it using Delayed Expansion and that didn't seem to work either.

I can use a For token in the substring, and I've figured out a work-around for what I want to do, but it would be much simpler if there was a way to directly use a variable.

Is this possible?

EDIT:

After much experimentation, it seems that enabling delayed expansion and using !String:~0,%x%! works.
User avatar
Simon Sheppard
Posts: 190
Joined: 2021-Jul-10, 7:46 pm
Contact:

Re: Is it possible to use variables in a substring operation?

Post by Simon Sheppard »

Thats a very interesting usage, you are using DelayedExpansion against a string expression rather than a variable I didn't realise that was possible, but it works!
User04
Posts: 2
Joined: 2022-Jan-23, 11:57 am

Re: Is it possible to use variables in a substring operation?

Post by User04 »

It's also possible to achieve the same result without delayed expansion. Since ECHO is an internal command, the following works:

Code: Select all

set String=1234567890
set /p x=Number of desired characters?
call echo %%String:~0,%x%%%
See also: The "Advanced Usage of :~" section in How-to: Extract part of a variable (substring)
Post Reply