This page is edited from the 1cmdfaq.txt faq-file contained in
my tscmd.zip
command line interface (CLI) collection. That zipped file has much
additional material, including a number of detached .cmd script
files. It is recommended that you also get the zipped version as a
companion.
Please see "
The Description and
the Index page" for the conditions of usage and other such
information.
179} How to replace an asterisk "*" in an environment variable?
Replacing a standard character in a command-line script is
straight-forward:
@echo off & setlocal enableextensions
set var=This is a string
echo %var%
echo %var
: =-%
endlocal & goto :EOF
The output will be:
C:\TEST>CMDFAQ
This is a string
This-is-a-string
However, the following will
not work as
one would expect
@echo off & setlocal enableextensions
set var=This*is*a*string
echo %var%
echo %var:*=_%
endlocal & goto :EOF
Adding a backslash or some other character would work
@echo off & setlocal enableextensions
set var=This
\*is
\*a
\*string
echo %var%
echo %var:
\*=-%
endlocal & goto :EOF
The output will be:
C:\TEST>CMDFAQ
This\*is\*a\*string
This-is-a-string
A Visual Basic Script (
VBScript)
aided command line script solution can be used without the
complications
@echo off & setlocal enableextensions
set var=This*is*a*string
echo %var%
>"%temp%\tmp$$$.vbs" echo WScript.Echo Replace("%var%","*","-")
for /f "delims=" %%a in ('
cscript //nologo "%temp%\tmp$$$.vbs"') do set varNew=%%a
for %%f in ("%temp%\tmp$$$.vbs") do if exist %%f del %%f
echo %varNew%
endlocal & goto :EOF
The output will be:
C:\TEST>CMDFAQ
This*is*a*string
This-is-a-string
The following, limited pure script solution is possible. The solution
is not generic, since one has to know in advance the number of
asterisk occurrences in the string.
@echo off & setlocal enableextensions
set var=This*is*a*string
for /f "tokens=1-4 delims=*" %%a in (
"%var%") do set varNew=%%a-%%b-%%c-%%d
echo %var%
echo %varNew%
endlocal & goto :EOF
The output will be:
C:\TEST>CMDFAQ
This*is*a*string
This-is-a-string
The following version, also based on an alt.msdos.batch.nt discussion,
is more generic, but not infallible (try with: set var=This**is**a**string)
@echo off & setlocal enableextensions
set var=This*is*a*string
echo %var%
:_loop
for /f "tokens=1,* delims=*" %%a in (
"%var%") do set var=%%a-%%b
if not "%var%"=="%var:**=%" goto :_loop
echo %var%
endlocal & goto :EOF