Page tree

Welcome to FreeSoftwareServers Confluence Wiki

Skip to end of metadata
Go to start of metadata

https://stackoverflow.com/questions/3001999/how-to-remove-trailing-and-leading-whitespace-for-user-provided-input-in-a-batch

External Function:

@ECHO OFF
CLS

CALL :Trim %2 %~1 
:Trim
SetLocal EnableDelayedExpansion
set Params=%*
for /f "tokens=1*" %%a in ("!Params!") do EndLocal & set %1=%%b
exit /b

Test:

@ECHO OFF
CLS

set myvar= FOO
CALL C:\tmp\trim_whitespace.cmd %myvar% myvar
echo %myvar%
PAUSE

Inside Script:

@ECHO OFF
CLS

SET var= FOO

CALL :Trim trimmed %var% 
ECHO %trimmed%
PAUSE

:Trim
SetLocal EnableDelayedExpansion
set Params=%*
for /f "tokens=1*" %%a in ("!Params!") do EndLocal & set %1=%%b
exit /b

Note: There are edge cases this won't work, check out SO for other examples & test before deploying!

  • No labels