Saturday 19 July 2008

Batch programming tip#11: Using The Substring Equivalent

As you know, most (all?) programming languages provide a substring() method of some sort which allows you to retrieve part of a string variable.

To do this in batch you can use the following syntax:
%var:~start% or
%var:~start,length%
where start is the index of the first character to retrieve (the first character in a string is indexed 0) and length is the length of the substring to retrieve. If no length is given the whole remaining string is shown.

In this example, we use a system variable %date% which holds the current system date and then echo the current system month and year.

@echo off

:get_year
echo System date: %date%
echo System month: %date:~8,2%
echo System year: %date:~11%
goto eof

:eof
echo Press any key to quit...
pause > NUL
goto blackhole

:blackhole


You can also use this method 'backwards'. Assume we didn't know the length of the %date% variable string, and wanted to retrieve the four last characters which represent the year.
We could then use the following syntax: %date:~-4% with a minus preceding the 4. This moves us back 4 characters from the end of the string, then (because no length has been specified) returns all the remainder until the end of the string. This is equivalent to: %date:~-4,4%

The drawback here is you cannot dynamically set the 'start' and 'length'. For this we need to use delayed expansion, which I'll get back to in a later post!

Until then, thoughts?

No comments:

Online Marketing
Add blog to our blog directory blog search directory Blog Directory Blogarama - The Blog Directory