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

时间:2013-02-14 18:16:29

标签: powershell powershell-v3.0

我正在使用以下脚本来获取逗号计数。

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

它返回,

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

我可以在Group列而不是@{Count=86}, ...中显示行号吗?

文件将有很多行,大多数行都有相同的逗号。我想对它们进行分组,以使输出线更小

1 个答案:

答案 0 :(得分:3)

你能用这样的东西吗?

$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}} 

如果您不想在组中多次使用“count”属性,则需要自定义对象。像这样:

$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) 
    }
}

输出:

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