Page 1 of 1

How to get a count of strings in a file

Posted: 16 Mar 2011 19:22
by Cleptography
I have a text file the file looks like this.

Code: Select all

Hello world this is the first string
Hello world this is the second string
Hello world this is the third string
World this is not enough strings


I want to get a count on how many times the sub string World
occurs in the file.
The output should look like
World=4

Thank You

Re: How to get a count of strings in a file

Posted: 16 Mar 2011 19:38
by ghostmachine4
Cleptography wrote:I have a text file the file looks like this.

Code: Select all

Hello world this is the first string
Hello world this is the second string
Hello world this is the third string
World this is not enough strings


I want to get a count on how many times the sub string World
occurs in the file.
The output should look like
World=4

Thank You



download gawk for windows and use this one liner



Code: Select all

C:\test>gawk "BEGIN{IGNORECASE=1}{m+=gsub(/world/,\"\")}END{print m}" file
4


Re: How to get a count of strings in a file

Posted: 16 Mar 2011 19:51
by Cleptography
Thank you ghost I am familiar with gawk, but this needs to be done using DOS only.

Re: How to get a count of strings in a file

Posted: 16 Mar 2011 20:47
by ghostmachine4
Cleptography wrote:Thank you ghost I am familiar with gawk, but this needs to be done using DOS only.


you mean you cannot download gawk , right? Well, in that case, use vbscript (or powershell) unless you are saying you are working with DOS 6.22 !

Code: Select all

Set objFS = CreateObject( "Scripting.FileSystemObject" )
strFile = WScript.Arguments(0)
Set objFile = objFS.OpenTextFile(strFile)
total = 0
Do Until objFile.AtEndOfLine
   strLine = objFile.ReadLine
      s = Split(strLine," ")
      For i=LBound(s) To UBound(s)
         If InStr( LCase( s(i)) , "world" ) > 0 Then
            total = total + 1   
         End If
      Next
Loop
objFile.Close
WScript.Echo "total: " & total


output

Code: Select all

C:\test>cscript //nologo test.vbs file
total: 4


Re: How to get a count of strings in a file

Posted: 16 Mar 2011 23:30
by Cleptography
Well Ghost thank you for your help I think...
...but this does what I need it to.

Code: Select all

@echo off&&setlocal

set str2find=world
set file=%~1
set token=0

for /f "tokens=*" %%- in (%file%) do (
   set str=%%-&&call :NEXT
)
goto :COUNT

:NEXT
for /f "tokens=1,*" %%a in ("%str%") do (
   set str=%%b
   set strfind=%%a
)
if /i "%strfind%"=="%str2find%" set /a token=%token%+1
if "%str%"=="" goto :eof
goto :NEXT

:COUNT
echo.%str2find% was found %token% times.