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?
String operations "inside" a FOR command
Moderator: DosItHelp
Re: String operations "inside" a FOR command
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.:
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
Nice one, thanks, that even answered one more question (setting AND accessing global variables inside FOR)
Re: String operations "inside" a FOR command
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 )
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 )
-
- Expert
- Posts: 391
- Joined: 19 Mar 2009 08:47
- Location: Iowa
Re: String operations "inside" a FOR command
I actually prefer many times to use the subroutrine trick instead of the call trick or delayedexpansion:
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.
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.