Sometimes it is useful to collect some stats about a text file you have. If you are using a modern text editor like Notepad++ or Geany, it probably has enough tools for all possible cases. However, if you are in a barebone Windows environment, then PowerShell can help you. Here is quick tip how to use it efficiently to calculate the number of words, chars and lines in a file.
PowerShell is an advanced form of command prompt. It is extended with a huge set of ready-to-use cmdlets and comes with the ability to use .NET framework/C# in various scenarios. If you have the skill to write scripts, you can create some very powerful ones to automate Windows. Recently, Microsoft made it available for Linux and OS X.
PowerShell comes with a useful built-in cmdlet Measure-Object. It calculates the property values of certain types of object. Measure-Object performs three types of measurements, depending on the parameters in the command. The cmdlet can count objects and calculate the minimum, maximum, sum, and average of the numeric values. For text objects, it can count and calculate the number of lines, words, and characters. This is exactly what we need.
All you need is to pass the file content to the input. For that purpose, you can combine Measure-Object with the another cmdlet Get-Content . The Get-Content cmdlet prints the content of the text file.
So, for our task, we can do the following.
- Open PowerShell
- Type or paste the following command:
Get-Content "F:\usb write protection (draft).txt" | measure -Line -Character -Word
Correct the file path portion to the file you need to measure. In my case, it shows the following output for my previous article text:
- Use the following command to count the same excluding spaces:
Get-Content "F:\usb write protection (draft).txt" | measure -Line -Character -Word -IgnoreWhiteSpace
That's it. This trick can be useful when you need to get the file content statistic but unable to get a suitable third party app for this task.