Batch file; Replace variable's spaces with hyphens
You're close.
@echo off
cls
echo Insert a string with spaces?
set string=
set /p string=
set string=%string: =-%
echo String is now %string%
See set /?
for details on variable manipulation.
Admin
Updated on June 25, 2022Comments
-
Admin almost 2 years
I've started another small Batch project, however I've encountered a bit of a dilemma. I use
set name=
followed byset /p name=
, to allow the user to give the input desired. However, I want the variable entered with spaces to then have the spaces replaced with hyphens (e.g. "hello world" becomes "hello-world").I've searched around and found many situations in which someone asks a similar question, however they are all using the
ren
command, which I have no use for due to not dealing with files.My current code is as follows:
@echo off Cls echo Insert a string with spaces? set string= set /p string=
I have also found a solution for renaming files that mentioned using
ren "!file!" "!file:_= !"
to change a file name's spaces to underscores (_
). However changing it toset name=!name:-= !
didn't work for me.How can I best replace spaces with hyphens in my batch file?
-
Admin over 10 yearsThanks, works like a charm. Also, I now see how setting a variable works, after the
:
, instead of acting off a guess. Thanks again!