Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of characters, words and lines in PowerShell

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.

like image 531
Mufa Sam Avatar asked Jan 10 '20 16:01

Mufa Sam


People also ask

How do I count the number of lines in a text file in PowerShell?

To count the total number of lines in the file in PowerShell, you first need to retrieve the content of the item using Get-Content cmdlet and need to use method Length() to retrieve the total number of lines.

How do I count strings in PowerShell?

Use Measure-Object to Get the String Length of a Variable in PowerShell. The Measure-Object cmdlet calculates the numeric properties of certain types of objects in the PowerShell. It counts the number of string objects' words, lines, and characters.

What is WC in PowerShell?

Word count (and more) using Measure-Object Linux has a command called wc that counts the number of lines and words in a file. Powershell has no such command but we can do something similar with the Measure-Object Cmdlet.


2 Answers

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.

like image 143
eyesec Avatar answered Oct 05 '22 19:10

eyesec


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

like image 32
Sage Pourpre Avatar answered Oct 05 '22 20:10

Sage Pourpre