Count the no of records in a file using positional search string

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
sujiconstantine
Posts: 3
Joined: 11 Aug 2017 03:42

Count the no of records in a file using positional search string

#1 Post by sujiconstantine » 11 Aug 2017 03:56

Hi
I need to count the number of records in a file that starts with the value 'A01'. If this value is found in other parts of the string, it should be ignored.

Can someone help please?

barnabe0057
Posts: 21
Joined: 04 Aug 2017 14:20
Location: France

Re: Count the no of records in a file using positional search string

#2 Post by barnabe0057 » 11 Aug 2017 06:50

Hi, try this :

Code: Select all

@echo off

set /a number=0

for /f "usebackq delims=" %%A in ("file.txt") do (echo %%A | findstr /b "A01" >nul && set /a number+=1)

echo number of records = %number%

pause
exit


dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Count the no of records in a file using positional search string

#4 Post by dbenham » 11 Aug 2017 14:31

Ugh - That is a horribly inefficient way to do it. You might not notice with a small file. But a large file will be painfully slow.

If all you want is to print the count to the screen, then

Code: Select all

findstr /b "A01" "file.txt" | find /n /v ""

If you want to capture the value in a variable, then

Code: Select all

for /f %%N in ('findstr /b "A01" "file.txt" ^| find /n /v ""') do set count=%%N


Dave Benham

barnabe0057
Posts: 21
Joined: 04 Aug 2017 14:20
Location: France

Re: Count the no of records in a file using positional search string

#5 Post by barnabe0057 » 11 Aug 2017 14:49

Thanks for the correction, I still have a few techniques to learn :oops:

sujiconstantine
Posts: 3
Joined: 11 Aug 2017 03:42

Re: Count the no of records in a file using positional search string

#6 Post by sujiconstantine » 14 Aug 2017 09:04

thank you for you help dbenham

Post Reply