I've found that all solution introduced here are not complete enough for me and does not work in one or another case.
CAUTION:
Seems the stackoverflow incorrectly handles tabulation characters (and loses other characters like \x01
) in the copy-pasted code, so the below code might not work if you copy it directly by CTRL+C. Use the link at the end to directly download the scripts.
trim_var.bat:
@echo off
rem drop the output variable value
if not "%~2" == "" if not "%~1" == "%~2" set "%~2="
if not defined %~1 exit /b 0
setlocal DISABLEDELAYEDEXPANSION
rem Load and replace a value quote characters by the \x01 character.
call set "RETURN_VALUE=%%%~1:"=%%"
:TRIM_LEFT_LOOP
if not defined RETURN_VALUE exit /b 0
if not ^%RETURN_VALUE:~0,1%/ == ^ / if not ^%RETURN_VALUE:~0,1%/ == ^ / goto TRIM_RIGHT_LOOP
set "RETURN_VALUE=%RETURN_VALUE:~1%"
if not defined RETURN_VALUE exit /b 0
goto TRIM_LEFT_LOOP
:TRIM_RIGHT_LOOP
if not defined RETURN_VALUE exit /b 0
if not ^%RETURN_VALUE:~-1%/ == ^ / if not ^%RETURN_VALUE:~-1%/ == ^ / goto TRIM_RIGHT_LOOP_END
set "RETURN_VALUE=%RETURN_VALUE:~0,-1%"
goto TRIM_RIGHT_LOOP
:TRIM_RIGHT_LOOP_END
rem recode quote and exclamation characters
set "__ESC__=^"
set __QUOT__=^"
set "__EXCL__=!"
set "RETURN_VALUE=%RETURN_VALUE:!=!__EXCL__!%"
set "RETURN_VALUE=%RETURN_VALUE:^=!__ESC__!%"
set "RETURN_VALUE=%RETURN_VALUE:=!__QUOT__!%"
rem safe set
setlocal ENABLEDELAYEDEXPANSION
for /F "tokens=* delims=" %%i in ("!RETURN_VALUE!") do for /F "tokens=* delims=" %%j in ("%%i") do (
endlocal
endlocal
if not "%~2" == "" (
set "%~2=%%j"
) else (
set "%~1=%%j"
)
)
exit /b 0
echo_var.bat:
@echo off
if not defined %~1 (
echo.%~2%~3
exit /b 0
)
setlocal DISABLEDELAYEDEXPANSION
rem Load and replace a value quote characters by the \x01 character.
call set "RETURN_VALUE=%%%~1:"=%%"
rem recode quote and exclamation characters
set "__ESC__=^"
set __QUOT__=^"
set "__EXCL__=!"
set "RETURN_VALUE=%RETURN_VALUE:!=!__EXCL__!%"
set "RETURN_VALUE=%RETURN_VALUE:^=!__ESC__!%"
set "RETURN_VALUE=%RETURN_VALUE:=!__QUOT__!%"
rem safe echo
setlocal ENABLEDELAYEDEXPANSION
for /F "tokens=* delims=" %%i in ("!RETURN_VALUE!") do for /F "tokens=* delims=" %%j in ("%%i") do (
endlocal
endlocal
echo.%~2%%j%~3
)
exit /b 0
test_trim_var.bat:
@echo off
setlocal DISABLEDELAYEDEXPANSION
set myvar1= 1 ! 2 ^| 3 ^& 4 ^^ 5 = 6 , 7 ; 8 * 9 # 0 %% 1 / 2 \ 3 ? 4 ^> 5 ^< 6 " 7
call "trim_var.bat" myvar1 myvar2
call "echo_var.bat" myvar1 - -
call "echo_var.bat" myvar2 - -
Output:
- 1 ! 2 | 3 & 4 ^ 5 = 6 , 7 ; 8 * 9 # 0 % 1 / 2 \ 3 ? 4 > 5 < 6 " 7 -
-1 ! 2 | 3 & 4 ^ 5 = 6 , 7 ; 8 * 9 # 0 % 1 / 2 \ 3 ? 4 > 5 < 6 " 7-
The latest implementation: https://github.com/andry81/contools/tree/HEAD/Scripts/Tools/std/trim_var.bat
Pros:
- Safely handles almost all specific characters like
!
, %
, ^
, "
.
Cons:
- The
"
character replaces by the \x01
character and might be affected by current code page (not tested).