Friday, September 9, 2011

Removing Unnecessary Trailing Spaces

Imagine: we have a variable with some string data, and we have to remove unnecessary spaces from the end of this variable. The code below shows how to solve this problem:

@echo off
setlocal
set "a=111 222 "

:loop
set /a n+=1
for /f "tokens=%n%" %%i in ("%a%") do (
if not "%%i"=="" set b=%b%%%i && goto:loop
)

set a=%b:~0,-1%
set b=
echo "%a%"


Of course, you have to change this code a bit before using it. You can do it with the help of our award-winning batch files editor. Hope you'll find this example useful.

2 comments:

  1. I find this easier:

    set MYVAR= Variable with spaces
    echo [%MYVAR%]
    echo.
    for /f "tokens=* delims= " %%A in ('echo %MYVAR% ') do set MYVAR=%%A
    set MYVAR=%MYVAR:~0,-1%
    echo [%MYVAR%]

    NOTE: you must "force" at least on trailing space in 'echo %MYVAR% '

    ReplyDelete
    Replies
    1. Excellent............Thank You very much.......

      Delete

Translate