Page 1 of 1
Count two strings in a text file
Posted: 02 Feb 2012 07:45
by Ken
How do I count two strings in a text file.
example text:
Hello Today is a good day
I would like to count all the words 'Hello' and 'day' and pipe it into another text file
example of output
Found the following words - Hello 5 times and day 10 times
Thank you for your help
Ken
Re: Count two strings in a text file
Posted: 02 Feb 2012 11:46
by Ed Dyreen
'
This counts occurrences in a single variable, for files it's a little bit more complicated, I don't have time right now
Code: Select all
@echo off &setlocal enableDelayedExpansion
set "$=Hello Today is a good day,Hello Today is a good day,Hello Today is a good day"
set/ac=0
:count ()
:: (
if defined $ for %%? in ("!$!") do (
set "$=!$:*day=!"
if "!$!" neq "%%~?" set/ac+=1&goto :count
)
:: )
echo.count=%c%_
pause
sorry
search.php
Re: Count two strings in a text file
Posted: 02 Feb 2012 21:03
by Aacini
Just one detail: you want not to count
strings, but
words, that is, strings enclosed in spaces or delimited by comma, semicolon or point, right? Otherwise, the "Today" will be counted as "day"!
The Batch file below correctly works if the file does not include equal-signs:
Code: Select all
@echo off
setlocal EnableDelayedExpansion
set Hello=0
set day=0
rem Read and process all the lines in the file
for /F "delims=" %%l in (thefile.txt) do (
rem Enclose next line between $ delimiters
set "line=$$%%l$$"
rem Change word separators ( ,;.) by $ delimiter
set "line=!line: =$!"
set "line=!line:,=$!"
set "line=!line:;=$!"
set "line=!line:.=$!"
rem Review each word
for %%w in (Hello day) do (
rem Replace the word by a separator
set "newLine=!line:$%%w$= !"
rem If the word was in the line...
if not "!newLine!" == "!line!" (
rem ... count how many times
for %%t in (!newLine!) do set /A %%w+=1
set /A %%w-=1
)
)
)
echo Hello %Hello% times and day %day% times
Re: Count two strings in a text file
Posted: 03 Feb 2012 14:24
by Ken
Aacini and Ed Dyreen
Thank you for your help with this code.
Ken
Re: Count two strings in a text file
Posted: 10 Feb 2012 07:34
by foxidrive
Here's another method. It is case insensitive and it will also match words like Hellocopter and daytona
It will also not count this as two occurrences of day "Today is Sunday" but will only count it as 1.
Code: Select all
@echo off
for /f %%a in ('find /c /i "Hello" ^<"file.txt"') do set hello=%%a
for /f %%a in ('find /c /i "day" ^<"file.txt"') do set day=%%a
echo Hello %hello% times and day %day% times