Re: How to replace "=","*", ":" in a variable
Posted: 20 Feb 2014 10:44
I was investigating this in order to solve a related "=" issue, and that issue provided me a tool to solve this:
When command line arguments are tokenized into %1, %2, etc., "=", ";" and "," are treated as token delimiters and not preserved. If I take a string, change the spaces, commas and semicolons into other, distinctive strings, I can then pass the string to a call and I know that an equals sign was in between each token that the call receives.
The below example does these replacements:
"," -> "#-comma-#"
";" -> "#-semicolon-#"
"=" -> "#-equal-#"
When command line arguments are tokenized into %1, %2, etc., "=", ";" and "," are treated as token delimiters and not preserved. If I take a string, change the spaces, commas and semicolons into other, distinctive strings, I can then pass the string to a call and I know that an equals sign was in between each token that the call receives.
The below example does these replacements:
"," -> "#-comma-#"
";" -> "#-semicolon-#"
"=" -> "#-equal-#"
Code: Select all
@if DEFINED _echo @( echo on ) else @( echo off )
call :replaceSpecialCharacters %*
@echo Special characters substituted out: %__test_Out%
set __test_Out=%__test_Out:#-comma-#=,%
set __test_Out=%__test_Out:#-semicolon-#=;%
set __test_Out=%__test_Out:#-equal-#==%
@echo Special characters substituted back in: %__test_Out%
goto :EOF
:replaceSpecialCharacters
@REM when arguments are tokenized [%1, %2, etc.], "=", "," and ";" are treated
@REM as a space and lost. %* isn't modified, so we use it to preserve the
@REM exact command line arguments when we have it tokenized.
@REM Returns: __test_Out, which is the passed in argument string with these
@REM substitutions:
@REM "," -> "#-comma-#"
@REM ";" -> "#-semicolon-#"
@REM "=" -> "#-equal-#"
set __test_In=%*
set __test_In=%__test_In: =#-space-#%
set __test_In=%__test_In:,=#-comma-#%
set __test_In=%__test_In:;=#-semicolon-#%
call :replaceEquals %__test_In%
set __test_Out=%__test_Out:#-space-#= %
goto :EOF
:replaceEquals
set __test_Out=
:replaceLoop
set __test_Arg=%1
if NOT DEFINED __test_Arg goto :endReplaceLoop
if DEFINED __test_Out (
set __test_Out=%__test_Out%#-equal-#%__test_Arg%
) else (
set __test_Out=%__test_Arg%
)
shift
goto :replaceLoop
:endReplaceLoop
goto :EOF
Code: Select all
c:\>test.cmd 1 foo,bar=baz;fip 3
Special characters substituted out: 1 foo#-comma-#bar#-equal-#baz#-semicolon-#fip 3
Special characters substituted back in: 1 foo,bar=baz;fip 3