Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch Script "for /f ..."

Tags:

batch-file

cmd

for /F "skip=n tokens=3 delims= " %%i in (myfile.txt) do echo %%i

Is it possible for skip=n ... to be a variable like skip=%test% ... where %test% has an integer value?

So I'm trying to add a column of data and the location of this table in the file is given by a string.

For Eg:

$startTable 

0 1 4

1 2 4

2 1 4 

$endTable 

So the location of this table is given by the line number associated with $startTable. I have the value of this stored in a variable(!test!) so I need the skip=!test! and then I start adding the third column until I hit $endTable.

When I try;

for /f "skip=!test! tokens=3 delims= " %%j in (!INPUTFILE!) do (
echo %%j
if %%j == "$endTable" goto :break
set /a test2+=%%j
)
:break

I get the following error;

!test! tokens=3 delims= " was unexpected at this time.

-GK

like image 1000
GK-F3D Avatar asked Mar 04 '26 14:03

GK-F3D


2 Answers

for doesn't like to take the delayed expansion syntax inside the parameters. That should be fine, since you don't need it. Use the standard % wrapped variable, instead - that's what Michael and Jebego's examples are using.

If you really want to use the delayed expansion version, you'll need a temp variable to do it:

set for_parameters="skip=!test! tokens=3 delims= "
for /f %for_parameters% %%j in (!INPUTFILE!) do ( echo %%j

EDIT: Here's what I'm running, trying to stay close to your original parameter names. I changed the input to show that %j is updating and which rows are parsed.

stackoverflow_input.txt

$startTable

0 1 3

1 2 4

2 1 5

$endTable

stackoverflow1.bat

@setlocal enabledelayedexpansion
@echo off
set INPUTFILE=stackoverflow_input.txt
set test=3
set test2=0
set for_parameters="skip=!test! tokens=3 delims= "
for /f %for_parameters% %%j in (!INPUTFILE!) do (
echo %%j
if %%j == "#endTable" goto :break
set /a test2+=%%j
)
:break
echo Sum: %test2%
endlocal

stackoverflow2.bat

@setlocal enabledelayedexpansion
@echo off
set INPUTFILE=stackoverflow_input.txt
set test=3
set test2=0
for /f "skip=%test% tokens=3 delims= " %%j in (!INPUTFILE!) do (
echo %%j
if %%j == "#endTable" goto :break
set /a test2+=%%j
)
:break
echo Sum: %test2%
endlocal

Results (verified same on Win 7, Server 2008R2, Server 2003, and Win XP SP3):

D:\temp>stackoverflow1.bat
4
5
Sum: 9

D:\temp>stackoverflow2.bat
4
5
Sum: 9

If command extensions are disabled, you'll instead get: /f was unexpected at this time.

like image 160
Jeremy Murray Avatar answered Mar 06 '26 07:03

Jeremy Murray


Yes.

set num=2
for /F "skip=%num% tokens=3 delims= " %%i in (myfile.txt) do echo %%i

This will skip the first two lines. You could have just tried to add the variable!

like image 26
Jeff Gortmaker Avatar answered Mar 06 '26 05:03

Jeff Gortmaker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!