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
Count two strings in a text file
Moderator: DosItHelp
Re: Count two strings in a text file
'
This counts occurrences in a single variable, for files it's a little bit more complicated, I don't have time right now
sorry search.php
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
Code: Select all
for /?
Re: Count two strings in a text file
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:
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
Aacini and Ed Dyreen
Thank you for your help with this code.
Ken
Thank you for your help with this code.
Ken
Re: Count two strings in a text file
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.
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