Page 1 of 1

Using a Variable in String Manipulation

Posted: 06 Dec 2011 23:30
by alleypuppy
Hello,

I have a batch file that loops n amount of times until an IF statement is true. Each time it loops, it sets a variable to a new value (set /a num+=1). I want to use this variable (num) as part of a string manipulation number:

Code: Select all

IF /I %VAR:~%num%,1%=="A" [do commands]
This, however, does not seem to work.
I've also tried:

Code: Select all

SETLCOAL ENABLEDELAYEDEXPANSION
IF /I !VAR:~%num%,1!=="A" [do commands]
This does not seem to work either. Perhaps I am using DelayedExpansion incorrectly, but I don't know because I'm still not all that familiar with how DelayedExpansion works.

Thanks for any help!

Re: Using a Variable in String Manipulation

Posted: 07 Dec 2011 01:17
by orange_batch
You're on the right track.

The first case doesn't work because, command prompt reads from % to % to determine variables:
IF /I %VAR:~%num%,1%=="A" [do commands]

With delayed expansion, it reads as:
IF /I !VAR:~%num%,1!=="A" [do commands]

This should work, except the problem is there is a syntax error. You cannot expose a comma to command prompt in the comparison. So either enclose both sides of the comparison in quotation marks (disables special character handling) or escape the problematic character using a caret ^.

IF /I "!VAR:~%num%,1!"=="A" [do commands]

or

IF /I !VAR:~%num%^,1!==A [do commands]

Remember that the quotation marks are included in the comparison, so they need to be present on both sides appropriately.

By the way, you mis-typed SETLOCAL as SETLCOAL.

Lastly, it's only needed for commas or special characters like &|<>, so quotation marks aren't needed in this example:

Code: Select all

setlocal enabledelayedexpansion
set var=ABCDE
if !var:~1!==BCDE echo The characters following the first one in var are BCDE.
if !var:~-1!==E echo Last character of var is E.

Re: Using a Variable in String Manipulation

Posted: 07 Dec 2011 13:48
by alleypuppy
Great! Thanks!
By the way, you mis-typed SETLOCAL as SETLCOAL.
Whoops! :shock:
The code that I posted was just an example, however, it isn't an actual part of my batch file, so it wouldn't have made a difference either way, but I'm glad you pointed that out!

Re: Using a Variable in String Manipulation

Posted: 09 Dec 2011 11:23
by dbenham
orange_batch wrote:Lastly, it's only needed for commas or special characters like &|<>, so quotation marks aren't needed in this example:

It is also needed for = when doing search and replace with delayed expansion. I try to always use the quotes when doing any comparison using delayed expansion just so I don't get caught.

Dave Benham

Re: Using a Variable in String Manipulation

Posted: 09 Dec 2011 18:11
by orange_batch
Yep that too, that's what I meant by "like" :) I never have a full list of problematic characters in my head. :o