这是国外某大学QA的一道作业题,读取mainlog文件中的每一行信息,并获取有效的信息,也就是每条信息中第四个@后面的内容,然后进行分类与计数,要求是用Perl写,但我是用PowerShell完成的,文件截图如下:
代码如下:
1 <# 2 $logPath = "C:\Users\tylan\Desktop\mainlog.txt" 3 #> 4 function CheckInfo 5 { 6 param($logPath) 7 $logContent = Get-Content $logPath 8 $reg = "^[email protected][email protected][email protected][email protected]+$" 9 $categories = "","" 10 foreach($log in $logContent) 11 { 12 if($log -match $reg) 13 { 14 $partialLog = $log.split("@") 15 $category = $partialLog[4] 16 $categories += $category 17 } 18 } 19 $sortResult = $categories|Sort-Object|Get-Unique 20 foreach($cate in $sortResult) 21 { 22 $cate|Add-Member -MemberType NoteProperty -Name "cateCount" -Value 0 23 } 24 foreach($category in $categories) 25 { 26 foreach($cate in $sortResult) 27 { 28 if($category -eq $cate) 29 { 30 $cate.cateCount ++ 31 } 32 } 33 } 34 foreach($cate in $sortResult) 35 { 36 if($cate -ne "") 37 { 38 $cate + " : " + $cate.cateCount 39 } 40 } 41 } 42 $logPath = "C:\Users\tylan\Desktop\mainlog.txt" 43 CheckInfo $logPath
测试结果如下:
时间: 2024-10-12 19:22:52