Batch Script "for /f ..."
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 locati开发者_如何学Goon 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
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.
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!
Yes. This will echo the 4th and subsequent lines of test.txt
set sk=3
for /f "skip=%sk% delims=" %%L in (test.txt) do (
echo %%L
)
精彩评论