Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace character of string in batch script

Tags:

batch-file

I need to replace character * from a string which is some what like this:
*10.*31.**2.*65

I want to remove all the * from this string using batch script.

like image 546
Jimmy Avatar asked Mar 15 '13 20:03

Jimmy


2 Answers

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.

like image 66
mgthomas99 Avatar answered Sep 22 '22 01:09

mgthomas99


You don't need an entire script for this. You just need a single for /f loop.

C:\Users\rojo>set test=*10.*31.**2.*65

C:\Users\rojo>echo %test%
*10.*31.**2.*65

C:\Users\rojo>for /f "tokens=1-4 delims=.^*" %I in ("%test%") do @set test=%I.%J.%K.%L

C:\Users\rojo>echo %test%
10.31.2.65

If you want to put the for loop into a batch script, use %%I, %%J, %%K and %%L instead of the single percents.

like image 23
rojo Avatar answered Sep 22 '22 01:09

rojo