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

标签 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 的强大功能,我非常喜欢有更好的方法。谢谢!

最佳答案

使用您当前的方法,您将为每个用户从磁盘读取一次文件。最好只扫描一次文件,一次收集所有用户。

听起来您没有提前获得用户列表,您基本上需要扫描 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

关于string - Powershell,计算文本文件中的字符串出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13997777/

相关文章:

java - 忽略分割字符串的第一部分

python - 添加前导零 Python

C: 如何将字符串存储到 “char *myArray[100]” 数组中?

string - 在vc++中将 'System::String ^'转换为 'const char *'

c# - 如何从字符串中删除枚举?

powershell - 使用 wsl 互操作性时如何加载 .bashrc?

Powershell,查看(循环)所有驱动器

powershell - 使用 NETSTAT 为已建立的事件 TCP 连接获取外部地址名称

azure - 如何使用自动化帐户 PowerShell Runbook 重置 Azure 服务主体的凭据?

powershell - 如何使用 PowerShell 脚本在 Windows 任务计划程序中配置 "If the task is already running, then the following rule applies"?