Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search number of times a string occurs in text file

I am trying to go read a text file and count the number of times a phrase/string (not word) occurs in the text file, but so far what I have is this:

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objFile = objFSO.OpenTextFile("D:\VBscript project\testing.txt", ForReading)
strContents = objFile.ReadAll
objFile.Close

i = 0

arrLines = Split(strContents, "")

For Each strLine in arrLines
    If InStr(strLine, "hi there") Then
        i = i + 1
    End If
Next

WScript.Echo "Number of times word occurs: " & i

This will only allow me to count the number of times a word occurs, which does not work when I try to tweak it to count phrases.

like image 518
OSY Avatar asked Dec 15 '22 05:12

OSY


2 Answers

Consider the below example:

strPath = "D:\VBscript project\testing.txt"
strPhrase = "hi there"

strContent = ReadTextFile(strPath, 0)
arrContent = Split(strContent, strPhrase)

MsgBox "Number of times phrase occurs: " & UBound(arrContent)

Function ReadTextFile(strPath, lngFormat)
    ' lngFormat -2 - System default, -1 - Unicode, 0 - ASCII
    With CreateObject("Scripting.FileSystemObject").OpenTextFile(strPath, 1, False, lngFormat)
        ReadTextFile = ""
        If Not .AtEndOfStream Then ReadTextFile = .ReadAll
        .Close
    End With
End Function

Note that Split-based method is case-sensitive.

like image 99
omegastripes Avatar answered Feb 23 '23 20:02

omegastripes


strPath = "D:\VBscript project\testing.txt"
strPhrase = "hi there"

strContent = ReadTextFile(strPath, 0)
arrContent = Split(strContent, strPhrase)

MsgBox "Number of times phrase occurs: " & UBound(arrContent)

Function ReadTextFile(strPath, lngFormat)
    ' lngFormat -2 - System default, -1 - Unicode, 0 - ASCII
    With CreateObject("Scripting.FileSystemObject").OpenTextFile(strPath, 1, False, lngFormat)
        ReadTextFile = ""
        If Not .AtEndOfStream Then ReadTextFile = .ReadAll
        .Close
    End With
End Function
like image 37
Sankar Karthi Avatar answered Feb 23 '23 19:02

Sankar Karthi