How to easily count output lines in cmd.exe with the builtin FIND tool.
When working in a command line environment it is sometimes very useful to be able to count the lines of output from different tools. Many Unix/Linux operating systems contains the wc tool with many options and there is no real builtin alternative in Windows, however some of same capabilities exists native in the Windows Command Prompt (cmd.exe).
In this short post we will see how we can use the FIND utility for counting lines in cmd.exe. The find tool, somewhat similar to grep in Unix, has been around since MS-DOS and is easy to use since it is included by default in every Windows installation.
Assume for example that we have a Windows Server and want to see how may TCP sessions that is active for the moment. This could be studied with the netstat command and piped into FIND to grep the established sessions.
netstat -nao | find /i “estab”
The output from this could quite overwhelming with hundreds of lines and we might only be interesting in the number of sessions. By just appending the switch /c to the command line we will get the number of open TCP sessions.
We will still use the filter (in this case look for the string “estab” to find only lines containing the ESTABLISHED state) but together with /c the tool will only display the number of matching lines.
Another short example could be the notice the number to locally cached dns records, see output above.
The /c option could also be used to count all lines that a commands leaves as output. For example we would like to know the number of groups in Active Directory. By using a pipe to FIND /v “” /c we want to see all lines that does not (/v) match the string “”, i.e. all lines and then count it. By using /v “” we will grep every non-blank line, which could be useful if the output strings are very different. If you have used the Unix tool wc this would be quite like wc -l.
Another example with a command that displays a very large number of output line would be the Event Logger command line tool wevutil. If just wanting to know the number of different logs in modern Windows system we could pipe the names of several hundreds of log files into FIND /v “” /c.
A final example could be that we have a log file or similar with perhaps thousands of lines in total and we quickly want to know the amount of lines with certain key phrases.
TYPE C:\Windows\Schedlgu.txt | FIND /i “task failure” /c
It should be noted that the Unix tool wc has a number of Win32 ports available for free, but often it is most useful to know what could be accomplished from the builtin tools available on all Windows, even legacy versions.