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

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%