Count the number of characters, words and lines in PowerShell
Asked Answered
M

4

19

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.

Merete answered 10/1, 2020 at 16:49 Comment(2)
the Measure-Object cmdlet CAN count lines, words, and chars. please add your code to the Question so we can see what needs changing.Groovy
It works. Unfortunately, Measure-Object seems to be much slower than wc.Nahum
M
29
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.

Milagro answered 17/1, 2020 at 15:16 Comment(1)
Also just cat [filename] | measure -w -c -l using the built-in aliases.Eal
F
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

Faction answered 10/1, 2020 at 17:18 Comment(0)
V
3

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

Villanelle answered 24/7, 2022 at 21:41 Comment(0)
O
1
type '.\filename.txt' | Measure-Object -Line -Word -Character

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

Ossian answered 28/6, 2022 at 23:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.