inputbatch-filewhitespacetrim

How to remove trailing and leading whitespace for user-provided input in a batch file?


I know how to do this when the variable is pre-defined. However, when asking for the user to enter in some kind of input, how do I trim leading and trailing whitespace? This is what I have so far:

@echo off

set /p input=:
echo. The input is %input% before

::trim left whitespace
for /f "tokens=* delims= " %%a in ("%input%") do set input=%%a
::trim right whitespace (up to 100 spaces at the end)
for /l %%a in (1,1,100) do if "!input:~-1!"==" " set input=!input:~0,-1! 

echo. The input is %input% after

pause

Solution

  • You need to enable delayed expansion. Try this:

    @echo off
    setlocal enabledelayedexpansion
    :blah
    set /p input=:
    echo."%input%"
    for /f "tokens=* delims= " %%a in ("%input%") do set input=%%a
    for /l %%a in (1,1,100) do if "!input:~-1!"==" " set input=!input:~0,-1!
    echo."%input%"
    pause
    goto blah