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

16
在Linux中,我们有“wc”命令,可以用来计算文件中的字符数、单词数和行数。
但是在PowerShell中是否有类似的命令呢?我尝试过使用Measure-Object命令,但它只能计算行数,无法统计字符和单词数量。

3
Measure-Object 命令可以计算行数、单词数和字符数。请将您的代码添加到问题中,以便我们看到需要更改的内容。 - Lee_Dailey
它可以工作。不幸的是,“Measure-Object”似乎比“wc”慢得多。 - Liang Zhang
4个回答

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

它计算文件中的字符数。

Get-Content [FILENAME] | Measure-Object -Word
它计算文件中单词的数量。
Get-Content [FILENAME] | Measure-Object -Line

它会统计文件中的行数。


4
同时,可以使用内置别名来执行 cat [filename] | measure -w -c -l 命令。 - ATOMP

4

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


2
如果您想要统计一个目录中所有文本文件中的单词数量:
Get-ChildItem <INPUT_FOLDER_PATH> -Recurse -Filter *.txt | Get-Content | measure -Word -Line - Character

enter image description here


1
type '.\filename.txt' | Measure-Object -Line -Word -Character

获取所有内容。对于基于文本的文件,type命令键入时间要少得多。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接