String operations "inside" a FOR command

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
AxZ
Posts: 3
Joined: 10 Mar 2010 09:33

String operations "inside" a FOR command

#1 Post by AxZ » 10 Mar 2010 10:19

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?

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: String operations "inside" a FOR command

#2 Post by aGerman » 10 Mar 2010 12:20

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

AxZ
Posts: 3
Joined: 10 Mar 2010 09:33

Re: String operations "inside" a FOR command

#3 Post by AxZ » 11 Mar 2010 07:19

Nice one, thanks, that even answered one more question (setting AND accessing global variables inside FOR) :)

AxZ
Posts: 3
Joined: 10 Mar 2010 09:33

Re: String operations "inside" a FOR command

#4 Post by AxZ » 01 Apr 2010 03:39

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 :))

avery_larry
Expert
Posts: 391
Joined: 19 Mar 2009 08:47
Location: Iowa

Re: String operations "inside" a FOR command

#5 Post by avery_larry » 05 Apr 2010 09:30

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.

Post Reply