Removing spaces from a variable in batch

user2313522 picture user2313522 · Apr 29, 2013 · Viewed 86.6k times · Source

I am writing a file to remove spaces from filenames in a folder and then put the result in a .txt file. I just get a result of "Echo is on." over and over.

This is what I have so far:

@echo ON
SET LOCAL EnableDelayedExpansion
For %%# in (*.*) do (
    SET var=%%~n#
    Set MyVar=%var%
    set MyVar=%MyVar: =%
    echo %MyVar%>>text.txt
)

Can someone tell me whats wrong?

Answer

zr870 picture zr870 · Jun 17, 2015

Removing all spaces (not just leading and trailing) can be done without using setlocal enabledelayedexpansionwith the following line:

set var=%var: =%

This works by replacing all spaces in the string with the empty string.

Source: DOS - String Manipulation