I write new function for removing spaces from a variable in batch.
Maybe there are proposals or remarks?
Code: Select all
@ECHO OFF
CALL :Trim " Spaces between words " Result
CALL :Trim "No_space" Result
CALL :Trim "Right space " Result
CALL :Trim " Left space" Result
CALL :Trim " a \ / : * ? ' "" < > | ` ~ @ # $ [ ] & ( ) + - _ = z " Result
GOTO :EOF
REM========================================================
REM Function remove leading and ending spaces
:Trim
SETLOCAL
SET localInput=%1
REM Exclamation mark "!" change for "EnableDelayedExpansion'
SET localInputChange=%localInput:!=^^^!%
SETLOCAL ENABLEDELAYEDEXPANSION
SET localResult=
FOR /F %%* in ('ECHO(%localInputChange: ="^&ECHO("%') DO (
IF %%* NEQ "" (
REM If variable not defined - not add leading space
REM And ending spaces not add, because they add to word
IF NOT DEFINED localResult (SET "localResult=%%~*"
) ELSE SET "localResult=!localResult! !spaces!%%~*"
SET spaces=
)
REM Count spaces between word
IF %%* EQU "" SET "spaces= !spaces!"
)
REM Only for testing
ECHO.&& ECHO input=[!localInput:~1,-1!]&& ECHO result=[!localResult!]
ENDLOCAL && SET "%~2=%localResult%"
ENDLOCAL
GOTO :EOF
I think, this is a good idea and universal method , because no matter the length of the text and uses one loop.
This samples is this site.
Trim Right - Trim spaces from the end of a string via "FOR" command
Code: Select all
set str=15 Trailing Spaces to truncate &rem
echo."%str%"
for /l %%a in (1,1,31) do if "!str:~-1!"==" " set str=!str:~0,-1!
echo."%str%"
Trim Left - Trim spaces from the beginning of a string via "FOR" command
Code: Select all
set str= 15 Leading spaces to truncate
echo."%str%"
for /f "tokens=* delims= " %%a in ("%str%") do set str=%%a
echo."%str%"