Page 1 of 1

String operations "inside" a FOR command

Posted: 10 Mar 2010 10:19
by AxZ
Hi guys, 1st post, quite thrilled if someone knows about this :)

Normal string operation in a batch:
I do "set x=abcdefg"
then, "echo %x:~2,3%" would return "cde"

A FOR command in a batch script uses variables like "%%a" "%%b" ...
How can I use string operations on them like shown above?

Re: String operations "inside" a FOR command

Posted: 10 Mar 2010 12:20
by aGerman
It's impossible with the dynamic variables of a FOR loop. You need a regular variable. To process this variable during the runtime of the loop you need "SetLocal EnableDelayedExpansion" or the CALL trick.
e.g.:

Code: Select all

@echo off &setlocal
set "myString=123 abcdefg"

for /f "tokens=2" %%a in ("%myString%") do set "x=%%a" &call echo %%x:~2,3%%

pause

Re: String operations "inside" a FOR command

Posted: 11 Mar 2010 07:19
by AxZ
Nice one, thanks, that even answered one more question (setting AND accessing global variables inside FOR) :)

Re: String operations "inside" a FOR command

Posted: 01 Apr 2010 03:39
by AxZ
Hi again, one more question related to this came up:

If I need to access the variable inside the FOR loop with an IF command, is there a way to realize that without a procedure call?

In other words:
I can do "call set" or "call echo" inside the FOR loop, but I can't do "call if"

EDIT:
ok, i learned about "setlocal enabledelayedexpansion", this solved the issue (for now :))

Re: String operations "inside" a FOR command

Posted: 05 Apr 2010 09:30
by avery_larry
I actually prefer many times to use the subroutrine trick instead of the call trick or delayedexpansion:


Code: Select all

@echo off
for %%a in (abce efge ieks eiw) do call :process %%a
echo Your other code here
goto :eof

:process
set tmp_var=%1
echo %tmp_var:~2,3%
goto :eof


Effectively, this pulls the "guts" of the for loop out of the parentheses so you don't have to worry about the variables getting expanded one time when the for loop is run.