Replace character of string in batch script

@ECHO OFF
SETLOCAL
SET mystring=*10.31.*2.*65
:deaster
FOR /f "tokens=1* delims=*" %%i IN ("%mystring%") DO (
   SET mystring=%%j
   IF DEFINED mystring (
      SET mystring=%%i%%j
      GOTO deaster
   ) ELSE (
      SET mystring=%%i
   )
)
ECHO result=%mystring%=

You can simplify the removal process to one line. For example, if I had a string like this:

set string=hello!

and I wanted to remove the "!" in it, I can just do

set string=%string:!=%

The string will now have the value "hello" instead of "hello!"

edit: As jeb pointed out in the comments, you can't replace "*" using this method. This is because * is a wildcard character for batch file pattern matching (brilliant explanation of it here). I did not know this at the time of posting this answer as I assumed this replacement method worked for all input strings. If you specifically need to replace *, I'd recommend following magoo's answer. Otherwise, I will be keeping this answer up for those who need a general, short, one-liner solution to batch string replacements.

Tags:

Batch File