我得到了一个具有以下布局的文本文件,
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/