Powershell,计算文本文件中的字符串出现次数

时间:2012-12-21 22:04:17

标签: string powershell

我有一个包含以下布局的文本文件,

Lorem Ipsum Lorem Ipsum Ipsum user:john
Lorem Ipsum user:peter
Lorem Ipsum Lorem Ipsum user:george
Lorem Ipsum user:john
Lorem Ipsum  vLorem Ipsum user:george
Lorem Ipsum user:john

我必须在Powershell V2上开发一个脚本来计算事件并构建一个包含以下内容的CSV,

john,3
george,2
peter,1

我计划通过文件循环,将每个用户保存在一个数组中,然后使用get-content和一个模式计算出现次数,例如:

#assumming i was able to fill the array in some way :)
$users =@('john','peter', 'george')
for each ($user in $users)
{
     $count = get-content .\myfile.txt | select-string -pattern "user:$user"
     write-host $count
}
#save the CSV

有意义吗?我很满意你的提示和技巧。了解Powershell的强大功能我非常喜欢用户,这是一种更好的方法。谢谢!

2 个答案:

答案 0 :(得分:3)

使用您当前的方法,您将为每个用户从磁盘读取一次文件。扫描文件一次可能会更好,并且一次性收集所有用户。

听起来你提前没有用户列表,你基本上需要扫描像user:<username here>这样的字符串,并保持你找到的不同用户名的运行记录。

这是一个应该完成基本工作的功能:

function GetUserCounts($fileName)
{
  $userCounts = @{}

  switch -regex -file $fileName
  {
    '\buser:([a-zA-Z]+)\b' {
       $userName = $matches[1]
       $userCounts[$userName] = [int]$userCounts[$userName] + 1
    }
  }

  $userCounts.GetEnumerator() | select Name,Value
}

那么你可以像这样创建一个CSV:

PS> GetUserCounts .\myfile.txt | Export-Csv .\counts.csv

答案 1 :(得分:0)

以下是使用Group-Object cmdlet的另一个选项:

Get-Content lorem.txt | 
Foreach-Object {$_ -replace '^.+user:(.+)$','$1' } | 
Group-Object -NoElement
相关问题