31 January 2008

Cmd.exe Environment Variables with Colon and Tilde

Some commands in Windows cmd.exe batch files have a leading tilde (~) character or a trailing colon-tilde (:~) pair of characters attached to environment variable names. What's the purpose of these characters?

Trailing Colon-Tilde Pair

You can find more about colon-tilde in the help using set /?. Briefly, you can …

  • Slice a string in a variable: %NAME:~s,n where s is the start position (zero-offset) and n is the number of characters. If s is negative, then the offset starts from the right side minus 1 (i.e. -1 refers to the rightmost character). If n is negative, then length - n characters, are extracted.

  • Replace a substring with another string in a variable: %NAME:s1=s2% where s1 is substring to be replaced and s2 is the replacement.

Leading Tilde

The leading tilde is used to decompose elements in a batch file parameter formatted as a path, such as the parent directory or file extension. The best reference is Frequently Asked Questions Regarding The Windows 2000 Command Processor, "How do I parse a file name parameter into its' constituent parts?" (sic). Note that you can only use a leading tilde for batch file parameters, not environment variables (!).

4-Mar-08. Another version of the reference is Frequently Asked Questions Regarding The Windows 2000 Command Processor. 09-Sep-02.