Ragnarok
Ragnarok

Reputation: 170

Substitute substring in cmd window

I have the following string in a batch file script:

ABCE#$1 TroubleMaker[FFFFF A=MyCountry US=1 CA=1 JP=1 EU=1

and it's stored in _var,when I do set _var=%_var:* A=% - it cuts all the characters before " A" (including the 'A') and i'm left with =MyCountry US=1 CA=1 JP=1 EU=1

how can I change the set command to cut also the = mark from the string?

tried set _var=%_var:*==% - didn't work.

Thanks.

Upvotes: 1

Views: 289

Answers (2)

Magoo
Magoo

Reputation: 80138

@ECHO OFF
SETLOCAL
SET "string=ABCE#$1 TroubleMaker[FFFFF A=MyCountry US=1 CA=1 JP=1 EU=1"

FOR /f "tokens=1*delims==" %%s IN ("%string%") DO SET "string=%%t"
ECHO "%string%"
GOTO :EOF

This assumes that you want to delete up to and including the initial =

Upvotes: 1

aschipfl
aschipfl

Reputation: 34959

The = disturbs the substring replacement syntax, because it contains a = on its own.


You could go for the following work-around:

set _var=%_var:* A=%
set _var=%_var:~1%

The second line constitutes the substring expansion syntax (type set /? for details), which splits off the first character, that is supposed to be a =.

This of course works only if the = immediately follows the A substring.


You can check whether the first character is = before removing it, like:

set _var=%_var:* A=%
if "%_var:~,1%"=="=" set _var=%_var:~1%

If you just want to search for the (first) = character and to ignore the A substring, you could establish a loop structure like this:

:LOOP
if "%_var%"=="" goto :END
if "%_var:~,1%"=="=" (
    set _var=%_var:~1%
    goto :END
) else (
    set _var=%_var:~1%
    goto :LOOP
)
:END

This cuts off the first character and checks whether it is a =. If it is, the remaining string is stored in _var and the loop is left; if not, the loop continues checking the next character. The first line is inserted to not hang in case the string does not contain a = character.

Upvotes: 1

Related Questions