计算 PowerShell 中的字符数、单词数和行数

Count the number of characters, words and lines in PowerShell

在 Linux 中,我们有 "wc" 命令,它允许我们计算文件中的字符数、单词数和行数。

但是我们在 PowerShell 中有类似的 cmdlet 吗?我试过的Measure-Object cmdlet只能统计行数,不能统计字数。

Measure-Object 正是这样做的。 您必须为要返回的字符、单词和行指定要测量的参数。

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

参考:Microsoft.Powershell.Utility/measure-object

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

它计算文件中的字符数。

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

它计算文件中的单词数。

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

它计算文件中的行数。