Sunday, July 8, 2007

Environment Variable Editing

Say you have and environment variable, and you want to tweak the value, change it a little bit, get the first few letters, or whatever.  You can do this using command processor's built-in variable substring and string substitution feature.

This is really useful feature that I like to use all the time.  Here's an example of how I can compose my own date string in the YYYY.MM.DD format out of the regular %DATE% environment variable that I covered here.

set MY_YYYY=%DATE:~-4%

set MY_MM=%DATE:~4,2%

set MY_DD=%DATE:~7,2%


The first line takes the substring of %DATE% starting from the 4th character from the end, which gives me the year.  The second line takes the two characters starting from position 4.  Similarly on the third line, I got the two characters starting from position 7.  The last line simply concatenates them together into the format I wanted.

I can use substring to determine if today is Sunday for example.

if /I "%DATE:~0,3%" EQU "Sun" (

    echo Today is Sunday


So that shows you how to do substring.  Another cool usage of this is in doing string substitution.  Here's an example where I am replacing the year with my own string.

set MY_DATE=%DATE:2007=9999%

This will replace the year 2007 with 9999.  You can also simply leave the substitution string empty to remove a string from the variable value.

set MY_DATE=%DATE:2007=%

That will remove all occurrences of 2007 from the value.  I usually find this really handy to remove certain directories from my PATH.

You can also use this for testing if a certain string exists in a variable.  Take a look at the following example where I want to see if today is Sunday like the earlier example, but using substring.

if "%DATE:Sun=%" EQU "%DATE%" (

    echo No, today is not Sunday

) else (

    echo Today is Sunday


As you can see, what I did there is remove the string Sun from the date, and if it is successfully removed, it means today is Sunday, and the condition will become false.  If it does not find the string Sun, the condition will be true and we know today is not Sunday.

No comments: