33

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.

44

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
| improve this answer | |
11

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.

| improve this answer | |
4
set var1=Abc_123
set var2=%var1:*_=%
echo %var2%
| improve this answer | |
  • 3
    What does this do specifically? – Pimp Juice IT Oct 29 '19 at 17:09
  • Oh, if you were asking how this code works: it removes everything before the number, preceded by an underscore. – Zimba Nov 23 '19 at 13:31
  • @Zimba is there a way to simply extend this to "last _"? Also where can I find this in any documentation? – TWiStErRob Jan 25 at 0:40
  • Ok, found a docs, added to answer. Questions still stands: how do I make * greedy? I used a good ol' IF NOT ... GOTO :replace, but would be nice if there was a better way. – TWiStErRob Jan 25 at 0:50
  • 1
    @TWiStErRob: I see. If you don't know how many _ there are, then loop to the last one, then set var – Zimba Jan 29 at 16:24
1

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.

| improve this answer | |
  • 2
    The question is not asking about Powershell or Perl – Zimba Oct 29 '19 at 13:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.