Batch file; Replace variable's spaces with hyphens

16,230

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.

Share:
16,230
Admin
Author by

Admin

Updated on June 25, 2022

Comments

  • Admin
    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 by set /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 to set name=!name:-= ! didn't work for me.

    How can I best replace spaces with hyphens in my batch file?

  • Admin
    Admin over 10 years
    Thanks, works like a charm. Also, I now see how setting a variable works, after the :, instead of acting off a guess. Thanks again!