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
A very short & easy solution i'm using is this:
Results in:
I'd like to present a compact solution using a call by reference (yes, "batch" has pointers too!) to a function, and a "subfunction":
I'm using the "Trim Right Whitespace" exactly working on my "Show-Grp-of-UID.CMD". :) Other idea for improvement are welcome.. ^_^
To improve on Forumpie's answer, the trick is using
%*
(all params) in the sub:Edit: Added echo of the TRIM subroutines params, to provide more insight
This strips leading and trailing spaces, but keeps all spaces between.
Details of %*: Batch Parameters
I did it like this (temporarily turning on delayed expansion):
This is very simple.
for
without any parameters considers spaces to be delimiters; setting "*" as thetokens
parameter causes the program to gather up all the parts of the string that are not spaces and place them into a new string into which it inserts gaps of its own.