Batch File Tips and Tricks – Getting Substrings
This is an article I wrote a long time ago. It was the most popular on my old website, so I thought I had better move it across to here just in case people still needed it.
I learnt this trick on a project where I needed to trim some text off the end of a variable in a Windows batch file. Most solutions I found involved a third party program using the string as an argument or piping the string into a text file. I found this; One of the simplest and most useful “unknown” batch file tricks that I think I’ve used in every batch file since.
How to get a substring of a variable in a Windows batch file.
To express a variable in a batch file you start and end the variable with % signs.
To trim a variable, you add :~p,n to the end of the name part of the variable.
where p is the starting position and n is the character length of the variable section you would like to store. If you use a negative for p, the position will count from the right side of the variable.
To get the current year:
%date% = Thu 30/03/2023
%date:~10,4% = 2023
It could also be formatted like this:
%date:~-4,4% = 2023
To get the last 3 characters of the computers name:
%computername% = SALES001
%computername:~-3,3% = 001