View unanswered posts | View active topics It is currently 01 Sep 2014 19:49



Post new topic Reply to topic  [ 2 posts ] 
How to extract characters from a string 
Author Message

Joined: 28 Apr 2011 19:31
Posts: 1
Post How to extract characters from a string
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.


28 Apr 2011 20:23
Profile
Expert

Joined: 12 Feb 2011 21:02
Posts: 1207
Location: United States (east coast)
Post Re: How to extract characters from a string
Starting with
yzip wrote:
Code:
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:
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:
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:
set mmm=!mths:~!posn!,3!

It is much like your original dilemma.

The solution in this case is:
Code:
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:
call echo %%mths:~%posn%,3%%


Hope that helps

Dave Benham


29 Apr 2011 12:53
Profile
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 


Who is online

Users browsing this forum: Bing [Bot], Google [Bot], Yahoo [Bot] and 9 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
Jump to:  
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group.
Forum style by Vjacheslav Trushkin for Free Forums/DivisionCore.