How to extract part of a string in Windows batch file?

Suppose I have a value such as "Abc_123" that's stored in a variable in a batch (cmd) file. I want to end up with a variable that contains only "123". Is there any built-in way to do this?

I'm not terribly picky about the method, or performance, as long as it's built in to a typical Windows (Vista/2008) system.


Use the substring syntax:

C:\Users\John>set string=Abc_123

C:\Users\John>echo %string%
Abc_123

C:\Users\John>echo %string:~4,3%
123

If you just want everything after the underscore (and do not necessarily know the length of the string or where the underscore is, but can rely on there being only one underscore), try:

for /f "tokens=2 delims=_" %%a in ("%STRING%") do (
  set AFTER_UNDERSCORE=%%a
)

Basically, your string will be split into tokens using the underscore as a delimiter (delims=_). Only the second one (tokens=2) will be passed (as variable %%a) to the for loop. The loop will only run once since you are dealing with a single string in this case.

If you want to save the stuff both before and after the underscore, try:

for /f "tokens=1,2 delims=_" %%a in ("%STRING%") do (
  set BEFORE_UNDERSCORE=%%a
  set AFTER_UNDERSCORE=%%b
)

Note that %%a is the variable for the first token of the split; %%b is the variable for the second token of the split.


set var1=Abc_123
set var2=%var1:*_=%
echo %var2%

If you find that the batch language isn't powerful enough to do what you want - and it likely won't take you too long to get to that point - you can use the Windows PowerShell. This isn't installed by default on all versions of Windows, but you can download it free of charge.

If you don't like the PowerShell language, there's Perl. You'll have to install that on all systems though. There are others too.