Loading...
 

Greg`s Tech blog

Substrings in Windows batch scripts

Thursday 22 of January, 2009
I needed a way to convert the contents of the %DATE% variable (which looks like: Thu 01/22/2009) into mmddyy format. The windows SET command can do this.
 Set Shortdate=%DATE:~4,2%%DATE:~7,2%%DATE:~12,2% 

So, let's disect it by looking at a smaller portion first. (Remember that Windows command shell variables are reference as No value assigned. When you use the Set command, the variable name can have modifiers)
Set Shortdate=%DATE:~4,2% 


%DATE% is the variable we are searching.
%DATE:~4 says to start at offset of four from the beginning of the string
,2% says return two characters.
So
 Set Shortdate=%DATE:~4,2%
 echo %Shortdate% 


Would print: 01 (assuming it is January in the US)
So we could string this mechanism together like this
 Set Shortdate=%DATE:~4,2%
 Set shortdate=%shortdate%%DATE:~7,2%
 Set shortdate=%shortdate%%DATE:~12,2% 

or really shorten the process as shown in the first example