Page 1 of 1

How to extract characters from a string

Posted: 28 Apr 2011 20:23
by yzip
Below is a sample dos batch file. I managed to compute the starting position (posn) to extract the character. But the set command unable to extract the characters form the string. Can a variable (%posn%) be used in the set Command?

set today=%date%
set mth=%today:~4,2%
set mths=janfebmaraprmayjunjulaugsepoctnovdec
SET /A posn=100%mth%%%100*3-3
set mmm=%mths:~%posn%,3%

Thanks in advance.

Re: How to extract characters from a string

Posted: 29 Apr 2011 12:53
by dbenham
Starting with
yzip wrote:

Code: Select all

set today=%date%
set mth=%today:~4,2%
set mths=janfebmaraprmayjunjulaugsepoctnovdec
SET /A posn=100%mth%%%100*3-3


... you have several options:

without delayed expansion

Code: Select all

call set mmm=%%mths:~%posn%,3%%

The variables are expanded in two passes because of the CALL. After the first pass %posn% is expanded to the number and %%mths%% becomes %mths% which is expanded on the second pass.

with delayed expansion

Code: Select all

setlocal enableDelayedExpansion
set mmm=!mths:~%posn%,3!

Either technique above is all you need for your example. But sometime you might find yourself in a position where you need both mths and posn to be expanded with delayed expansion (such as if posn were being set within a for loop.

The following will NOT work (assuming delayed expansion is already enabled)

Code: Select all

set mmm=!mths:~!posn!,3!

It is much like your original dilemma.

The solution in this case is:

Code: Select all

for %%n in (!posn!) do set mmm=!mths:~%%n,3!


One other point - expanding to a substring is not dependent on the set command. You can use the technique at any point. For example, if all you wanted to do was display the month without setting a variable, you could simply use:

Code: Select all

call echo %%mths:~%posn%,3%%


Hope that helps

Dave Benham