DosTips.com

A Forum all about DOS Batch
It is currently 30 May 2016 04:37

All times are UTC-06:00




Post new topic  Reply to topic  [ 2 posts ] 
Author Message
PostPosted: 28 Apr 2011 20:23 
Offline

Joined: 28 Apr 2011 19:31
Posts: 1
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.


Top
   
PostPosted: 29 Apr 2011 12:53 
Offline
Expert

Joined: 12 Feb 2011 21:02
Posts: 1638
Location: United States (east coast)
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


Top
   
Display posts from previous:  Sort by  
Post new topic  Reply to topic  [ 2 posts ] 

All times are UTC-06:00


Who is online

Users browsing this forum: Yahoo [Bot] and 7 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® Forum Software © phpBB Limited