A different method to trim spaces from a string

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Message
Author
probyn
Posts: 7
Joined: 23 May 2013 20:01

Re: A different method to trim spaces from a string

#16 Post by probyn » 17 Jul 2013 17:10

[quote="penpen"]@probyn
I've found an issue when executing:

Code: Select all

Z:\>SET TEST=   test   

Z:\>SET TEST_A=   test a   

Z:\>safeTrim TEST

Z:\>SET TEST
TEST=test a
TEST_A=   test a   

This could be fixed by adding a safe if "%1" == "TEST", also a %1 gatekeeper should be performed, so the whole code changes to:

Code: Select all

@echo off
setlocal enableDelayedExpansion
set x=%1
if not defined x exit /b 1

for /f "tokens=1* delims==" %%a in (
'set %1'
) do (
set call _TMP=%%x:%%a=%%
if not defined _TMP endlocal & call :exec %%b
)
goto :EOF
:exec
set %x%=%*


goto :EOF


Or just make one little change to line 4
≡≡≡≡≡begin c:\Cmd\test\safetrim.cmd≡≡≡≡≡
1. @echo off
2. set x=%1
3. for /f "tokens=1* delims==" %%a in (
4. 'set %1 ^|findstr /b /i /c:"%1="'
5. ) do call :exec %%b
6. goto :EOF
7. :exec
8. set %x%=%*
9. goto :EOF
≡≡≡≡≡end c:\Cmd\test\safetrim.cmd≡≡≡≡≡

Phil Robyn

Sponge Belly
Posts: 216
Joined: 01 Oct 2012 13:32
Location: Ireland
Contact:

Re: A different method to trim spaces from a string

#17 Post by Sponge Belly » 26 Aug 2014 14:08

Hello All! :)

I reread this topic and felt there must be a way to coax %* into right-trimming an arbitrary string. I played around with the code of some of the contributors and discovered that CALL doesn’t enforce a closing quote for the parameter passed to a subroutine. :shock:

The following kludgy code illustrates the phenomenon:

Code: Select all

@echo off & setlocal enableextensions disabledelayedexpansion
set ^"str=^^ ^^^^ %% ! ^&^"^& ^"^^^&^^<SP><TAB><SP>^"
set "str=%str:"=""%"

setlocal enabledelayedexpansion
set "str=!str:%%=%%%%!"
endlocal & set "str=%str%"

call :rsnip+res "%str%

setlocal enabledelayedexpansion
set "res=!res:""="!"
echo([!res!]
endlocal & endlocal & goto :eof

:rsnip
setlocal disabledelayedexpansion
set "var=%0"
set "var=%var:~7%"
set x=%*
set "x=%x:~1%"
set "x=%x:^^=^%"
endlocal & set "%var%=%x%" & exit /b 0


Of course, per cents and quotes have to be doubled before the call to the rsnip subroutine, carets must be halved inside rsnip, and quotes restored to their previous state afterwards. Or at least, that’s the only way I could get it to work. If anyone can optimise this arduous procedure, please let me know.

Laters!

- SB

Post Reply