13

In Linux we have the "wc" command which allows us to count the number of characters, words and lines in a file.

But do we have a similar cmdlet in PowerShell. The Measure-Object cmdlet I tried could only count the number of lines but not the characters and words.

Mufa Sam
  • 165
  • 1
  • 2
  • 6

4 Answers4

21
Get-Content [FILENAME] | Measure-Object -Character

It counts the number of characters in the file.

Get-Content [FILENAME] | Measure-Object -Word

It counts the number of words in the file.

Get-Content [FILENAME] | Measure-Object -Line

It counts the number of lines in the file.

eyesec
  • 226
  • 1
  • 3
4

Measure-Object do exactly that. You do have to specify the parameters you want measured for the characters, words and lines to be returned.

Example 3: Measure text in a text file

This command displays the number of characters, words, and lines in the Text.txt file. Without the Raw parameter, Get-Content outputs the file as an array of lines.

The first command uses Set-Content to add some default text to a file.

"One", "Two", "Three", "Four" | Set-Content -Path C:\Temp\tmp.txt
Get-Content C:\Temp\tmp.txt | Measure-Object -Character -Line -Word

Lines Words Characters Property
----- ----- ---------- --------
    4     4         15

Reference: Microsoft.Powershell.Utility/measure-object

Community
  • 1
  • 1
Sage Pourpre
  • 9,932
  • 3
  • 27
  • 39
2

If you want to count all words in all text files in a directory:

Get-ChildItem <INPUT_FOLDER_PATH> -Recurse -Filter *.txt | Get-Content | measure -Word -Line - Character

enter image description here

Andrei Drynov
  • 8,362
  • 6
  • 39
  • 39
1
type '.\filename.txt' | Measure-Object -Line -Word -Character

Gets you everything. type takes far less time to type for text based files.

Sam Watson
  • 11
  • 1