Removing spaces from a variable in batch

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
b360124
Posts: 1
Joined: 15 Oct 2017 03:57

Removing spaces from a variable in batch

#1 Post by b360124 » 15 Oct 2017 10:45

Hi,
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%"

Osmium Programming
Posts: 14
Joined: 16 Oct 2017 20:15

Re: Removing spaces from a variable in batch

#2 Post by Osmium Programming » 23 Jan 2018 00:48

In the set /? help thing, it says that you can replace strings and characters in a variable with a custom string or character. To remove the spaces from "hi there" in the variable a, run set a=%a: =%

To replace a's with b's, run set a=%a:a=b%

You get the point

It is case insensitive

Post Reply