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.

# Get the current day
Get-Date -UFormat "%d"
> 15

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.

%variable%

To trim a variable, you can add :~p,n to the end of the name part of the variable.

%variable:~p,n%
  • p is the starting position
  • n 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.

# Regular variable output
echo %date%
> 2023-09-15

# Get the current year
echo %date:~0,4%
> 2023

# Get the current day going forwards
echo %date:~8,2%
> 15

# Get the current day going backwards
echo %date:~-2,2%
> 15

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.

# Get the computer name
echo %computername%
> SYDSALESWEB037

# Get the region
echo %computername:~0,3%
> SYD

# Get the department
echo %computername:~3,5%
> SALES

# Get the instance
echo %computername:~-3,3%
> 037

Further reading

SS64 page on batch substrings

Microsoft documentation on Get-Date Powershell cmdlet