Home > Net >  Batch string replace after special character
Batch string replace after special character

Time:12-22

In batch, how can replace the substring after a special character.

@echo off

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

set var1=abc_123
set var3=%var1:_*=%
echo %var3%

output:

123
abc_123

In set var2=%var1:*_=%, the *match the abc, but in set var3=%var1:_*=% it doesn't work!

What's the difference between the two usage? How can I use * or something to replace the _123

CodePudding user response:

With the search/replace syntax it's not possible, because the asterix is used as wildcard only when it's the first character in the search expression, at any other position it's treated as normal character.

But for a single character it can be done with a FOR /F loop.
It splits the text by the delimiter character(s) into tokens.

FOR /F "tokens=1,* delims=_" %%L in ("%var1%") DO (
  set var3=%%L
)
echo %var3%

CodePudding user response:

If you're looking for simpler, then perhaps this is what you're looking to achieve:

Set "var1=abc_123"
Echo(%var1%
Set "var2=%var1:*_=%"
Echo(%var2%
Set "var3=%var1:_="&:"%"
Echo(%var3%

Simpler of course refers only to using expansion and replacement, not the understanding of the technique. If you want to learn more about the technique, please take a look at the examples in this external site thread.

  • Related