1.

Solve : Counter in for loop doesn't increment?

Answer»

To all,
I need to run a batch script to read in an input file and then print out how many lines it read. The problem is the counter doesn't INCREMENT. It keeps resetting back to zero but after the loop, it gets the RIGHT counter but just not inside the loop.

Please help. Thanks.

Here's the script:

set x=0
for /f %%i in (f.txt) do (
echo A, %x%
set /a x=x+1
echo %%i
echo B, x=%x%
)
echo C, x=%x%
:END

This is the output:

A, 0
hostname1
B, x=0
A, 0
hostname2
B, x=0
A, 0
hostname3
B, x=0
C, x=3Quote from: april on March 27, 2009, 05:13:34 AM

To all,
I need to run a batch script to read in an input file and then print out how many lines it read.
basically, you just need a LINE count of the file correct?
you can use one of these methods
1) use a unix tools like wc, gawk
Code: [Select]# wc -l < file
check out the link in my sig to download. (coreutils)
2) if you have constraints about "installing" tools, you can use vbscript
Code: [Select]Dim o
o=0
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile= "C:\test\file.txt"
Set objFile = objFS.OpenTextFile(strFile,1)
Do Until objFile.AtEndOfLine
strLine = objFile.ReadLine
o=o+1
Loop
WScript.Echo "number of lines: ",o
3) or you can use find
Code: [Select]find /c /v "" file
Oh God! Another "how do I make this batch work?" question answered by "Get a port of a Unix util".

Heaven forbid we should actually answer the *censored* question!

April, due to the way that cmd.exe expands variables at runtime, an ordinary variable which is set inside brackets (parentheses) such as in a loop or an extended IF statement, will expand to a blank.

You need to know about "delayed expansion". You enable it by putting this line before the loop

Code: [Select]setlocal enabledelayedexpansion
Then inside the loop you use exclamation marks instead of percent signs for those variables created or modified inside the loop. You can use percent signs for them after the loop has finished. So here is your code rewritten a bit


Code: [Select]setlocal enabledelayedexpansion
set x=0
for /f %%i in (f.txt) do (
echo A, !x!
set /a x=!x!+1
echo %%i
echo B, x=!x!
)
echo C, x=%x%
:ENDQuote from: DIAS DE verano on March 27, 2009, 08:09:08 AM
Oh God! Another "how do I make this batch work?" question answered by "Get a port of a Unix util".
as long as OP has no constraints, i don't think there's a problem with that. Quote from: ghostdog74 on March 27, 2009, 08:23:40 AM
as long as OP has no constraints, i don't think there's a problem with that.

I know you don't.


Discussion

No Comment Found