简体   繁体   English

计算每行中的逗号并在文本文件中显示行号

[英]Count the comma in each line and show the line numbers in a text file

I'm using the following script to get the comma counts. 我正在使用以下脚本来获取逗号计数。

Get-Content .\myFile | 
% { ($_ | Select-String `, -all).matches | measure | select count } | 
group -Property count

It returns, 它返回,

Count Name   Group
----- ----   -----
  131 85     {@{Count=85}, @{Count=85}, @{Count=85}, @{Count=85}...}
    3 86     {@{Count=86}, @{Count=86}, @{Count=86}}

Can I show the line number in the Group column instead of @{Count=86}, ... ? 我可以在“ Group列中显示行号,而不是@{Count=86}, ...吗?

The files will have a lot of lines and majority of the lines have the same comma. 文件将包含很多行,并且大多数行具有相同的逗号。 I want to group them so the output lines will be smaller 我想对它们进行分组,以便输出线会更小

Can you use something like this? 你可以使用这样的东西吗?

$s = @"
this,is,a
test,,
with,
multiple, commas, to, count,
"@

#convert to string-array(like you normally have with multiline strings)
$s = $s -split "`n"

$s | Select-String `, -AllMatches | Select-Object LineNumber, @{n="Count"; e={$_.Matches.Count}} | Group-Object Count

Count Name                      Group                                                                                                        
----- ----                      -----                                                                                                        
    2 2                         {@{LineNumber=1; Count=2}, @{LineNumber=2; Count=2}}                                                         
    1 1                         {@{LineNumber=3; Count=1}}                                                                                   
    1 4                         {@{LineNumber=4; Count=4}} 

If you don't want the "count" property multiple times in the group, you need custom objects. 如果您不想在组中多次使用“ count”属性,则需要自定义对象。 Like this: 像这样:

$s | Select-String `, -AllMatches | Select-Object LineNumber, @{n="Count"; e={$_.Matches.Count}} | Group-Object Count | % {
    New-Object psobject -Property @{
        "Count" = $_.Name
        "LineNumbers" = ($_.Group | Select-Object -ExpandProperty LineNumber) 
    }
}

Output: 输出:

Count    LineNumbers 
-----    ----------- 
2         {1, 2}   
1         3   
4         4 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM