How to find the number of occurrences of a string in file using windows command line? How to find the number of occurrences of a string in file using windows command line? windows windows

How to find the number of occurrences of a string in file using windows command line?


Using what you have, you could pipe the results through a find. I've seen something like this used from time to time.

findstr /c:"@" mail.txt | find /c /v "GarbageStringDefNotInYourResults"

So you are counting the lines resulting from your findstr command that do not have the garbage string in it. Kind of a hack, but it could work for you. Alternatively, just use the find /c on the string you do care about being there. Lastly, you mentioned one address per line, so in this case the above works, but multiple addresses per line and this breaks.


Why not simply using this (this determines the number of lines containing (at least) an @ char.):

find /C "@" "mail.txt"

Example output:

---------- MAIL.TXT: 96

To avoid the file name in the output, change it to this:

find /C "@" < "mail.txt"

Example output:

96

To capture the resulting number and store it in a variable, use this (change %N to %%N in a batch file):

set "NUM=0"for /F %N in ('find /C "@" ^< "mail.txt"') do set "NUM=%N"echo %NUM%


Very simple solution:

grep -o "@" mail.txt | grep -c .

Remember a dot at end of line!

Here is little bit more understandable way:

grep -o "@" mail.txt | grep -c "@"

First grep selects only "@" strings and put each on new line.

Second grep counts lines (or lines with @).

The grep utility can be installed from GnuWin project or from WinGrep sites. It is very small and safe text filter. The grep is one of most usefull Unix/Linux commands and I use it in both Linux and Windows daily.The Windows findstr is good, but does not have such features as grep.

Installation of the grep in Windows will be one of the best decision if you like CLI or batch scripts.