Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a huge files with e-mail addresses and I would like to count how many of them are in this file. How can I do that using Windows' command line ?

I have tried this but it just prints the matching lines. (btw : all e-mails are contained in one line)

findstr /c:"@" mail.txt

like image 952
Patryk Avatar asked Feb 16 '12 07:02

Patryk


People also ask

How do you count number of lines in a file in Windows command prompt?

The /c /v command counts all the lines in a file, not just lines that contain text characters.

How do you count in CMD?

3. How to count the files in a folder, using Command Prompt (cmd) You can also use the Command Prompt. To count the folders and files in a folder, open the Command Prompt and run the following command: dir /a:-d /s /b "Folder Path" | find /c ":".

How do I search for words within a file in Windows 10 command line?

Findstr is a built-in feature in Windows 10 that allows you to locate a file with specific text. You can search individual files or the entire directory with your search query. To learn all the parameters, you can simply run the “findstr /?” command from an elevated command prompt.


2 Answers

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.

like image 127
Adam S Avatar answered Oct 11 '22 03:10

Adam S


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%
like image 37
aschipfl Avatar answered Oct 11 '22 02:10

aschipfl