Question : Batch File: Remove spaces in variable

Hi there,

I am looking for a way to remove the spaces in a variable with less code as below.

For example, insted of     :  SET A=%%A && SET A=!A: =!
It would be something like :  SET A=!%%A: =!

Thanks for your help,
Rene



WORKING SCRIPT:
***************************************************************
@ECHO OFF

setlocal enabledelayedexpansion
set String=This      ,is ,    a     ,big sentence.

for /f "tokens=1-4 delims=," %%A in ('echo !String!') do (
  echo BEFORE: %%A %%B %%C %%D
  SET A=%%A && SET A=!A: =!
  SET B=%%B && SET B=!B: =!
  SET C=%%C && SET C=!C: =!
  SET D=%%D
)
echo AFTER: !A! !B! !C! !D!
pause


WANT TO DO SOMETHING LIKE THIS (BUT OF CORSE, IT DOES NOT WORK)
***************************************************************
setlocal enabledelayedexpansion
set String=This      ,is ,    a     ,big sentence.

for /f "tokens=1-4 delims=," %%A in ('echo !String!') do (
  echo BEFORE: %%A %%B %%C %%D
  SET A=!%%A: =!
  SET B=!%%B: =!
  SET C=!%%C: =!
  SET D=%%D
)
echo AFTER: !A! !B! !C! !D!
pause

Answer : Batch File: Remove spaces in variable

Unfortunately there's no way to do the enhanced variable substitution (like replacing characters, or extracting characters, etc with either parm variables (%1, %2, %3, ...) or FOR loop variables (%%A, %%B, %%C, ...).  Sad but true.

If you want to keep the mainline code a little cleaner you could do this approach using a called subroutine.  It trims any left or right spaces from the passed string, and stores the result in the named variable.

for /f "tokens=1-5 delims=," %%A in ("%String%") do (
  echo BEFORE: %%A %%B %%C %%D %%E
  call :Trim "%%A" A
  call :Trim "%%B" B
  call :Trim "%%C" C
  call :Trim "%%D" D
  call :Trim "%%E" E
)
echo AFTER : %A% %B% %C% %D% %E%
pause
exit /b

:Trim "input-string" return-variable
  set s=%~1
  for /F "tokens=* delims= " %%A in ("%s%") do set s=%%A
  for /L %%A in (1,1,50) do if "!s:~-1!"==" " set s=!s:~0,-1!
  set %~2=%s%
  exit /b

~bp
Random Solutions  
 
programming4us programming4us