VBSで正規表現を使って単語数をカウントしたあと削除し、最後に単語数を表示するスクリプトはこちら。
Dim objFSO, objFile, strContents, wordToFind, wordCount
Dim filePath
Dim objRegExp, matches
' 設定:対象の単語とファイル
wordToFind = "テスト" ' ← カウント&削除する単語を指定
filePath = "C:\path\to\your\input.txt" ' ← 対象ファイルを指定
' FileSystemObjectを作成
Set objFSO = CreateObject("Scripting.FileSystemObject")
' ファイルが存在するかチェック
If objFSO.FileExists(filePath) Then
' ファイルを読み込み
Set objFile = objFSO.OpenTextFile(filePath, 1) ' ForReading
strContents = objFile.ReadAll
objFile.Close
' 正規表現オブジェクトを作成
Set objRegExp = New RegExp
objRegExp.Pattern = "\b" & wordToFind & "\b" ' 単語単位で検索
objRegExp.IgnoreCase = True ' 大文字小文字を区別しない
objRegExp.Global = True ' 全ての一致を対象
' 単語のカウント
Set matches = objRegExp.Execute(strContents)
wordCount = matches.Count
' 単語を削除
strContents = objRegExp.Replace(strContents, "")
' 出現回数を追加
strContents = strContents & vbCrLf & "単語「" & wordToFind & "」の出現回数: " & wordCount
' ファイルを上書き
Set objFile = objFSO.OpenTextFile(filePath, 2) ' ForWriting
objFile.Write strContents
objFile.Close
WScript.Echo "処理完了!「" & wordToFind & "」の出現回数: " & wordCount
Else
WScript.Echo "指定したファイルが見つかりません。"
End If
' オブジェクト開放
Set objRegExp = Nothing
Set objFile = Nothing
Set objFSO = Nothing
コメント