Batch file substrings
I wrote this article a long time ago on my old blog, it was one of my most popular posts so I moved it here in case it’s still needed.
The world has changed a lot since this was written, Powershell exists now with much easier ways to get the same information as this post.
Here’s the original, mostly unchanged post.
I had a project where I needed to trim text off the end of a variable in a Windows batch file. Most solutions involve a third party program passing the string as an argument or piping the string into a text file and manipulating the file. However,
Variable substrings in Windows batch files
To express a variable in a batch file you start and end the variable with % signs.
To trim a variable, you can add :~p,n to the end of the name part of the variable.
p
is the starting positionn
is the number of characters to return, omit it out to return the rest.
If you use a negative for p
or n
, the position will count from the right side of the variable.
Examples
Windows command prompt provides a localized current date using the %date%
variable. This technique can be used to extract the components of the date, however, as the initial varible is formatted based on locale settings, it will likely change between systems.
This can work with any cmd variables. If you have a structured naming nomenclature within your organization, this can be used to get substrings about a system for conditions in a script. ie. Check the system is in Sydney before making a change.
For a naming convention of <3-digit region><5-digit department><3-digit service><3-digit instance>
the below would work.