シェル操作課題 (cut, sort, uniq などで集計を行う) 設問編 - Yamashiro0217の日記
を PowerShell でやってみたの続き(含書き直し)。
もっと簡潔にできそうな気もするんだけどよくわからんw
あと、cut 相当の関数をあらかじめ書いておいた方が良いかも。
-split 使った同様のパターンが頻出してるし。
server1,1343363124,30,/video.php
server2,1343363110,20,/profile.php
server3,1343363115,7,/login.php
server1,1343363105,8,/profile.php
server2,1343363205,35,/profile.php
server2,1343363110,20,/profile.php
server3,1343363205,30,/login.php
server4,1343363225,12,/video.php
server1,1343363265,7,/video.php
問1 このファイルを表示しろ
PS >Get-Content .\input.txt
問2 このファイルからサーバー名とアクセス先だけ表示しろ
PS > Get-Content .\input.txt|%{(($_ -split ",")[0,3]) -join ","}
server1,/video.php
server2,/profile.php
server3,/login.php
server1,/profile.php
server2,/profile.php
server2,/profile.php
server3,/login.php
server4,/video.php
server1,/video.php
問3 このファイルからserver4の行だけ表示しろ
PS > Get-Content .\input.txt|where {$_ -match"^server4"}
server4,1343363225,12,/video.php
問4 このファイルの行数を表示しろ
PS > Get-Content .\input.txt|Measure-Object|%{$_.count}
9
問5 このファイルをサーバー名、ユーザーIDの昇順で5行だけ表示しろ
PS > Get-Content .\input.txt| Sort-Object -Property @{Expression={($_ -split ",")[0]}; Ascending=$true},@{Expression={[int]($_-split ",")[2]}; Ascending=$true}| Select-Object -first 5
server1,1343363265,7,/video.php
server1,1343363105,8,/profile.php
server1,1343363124,30,/video.php
server2,1343363110,20,/profile.php
server2,1343363110,20,/profile.php
問6 このファイルには重複行がある。重複行はまとめて数え行数を表示しろ
PS > Get-Content .\input.txt|group-object|Measure-Object|%{$_.count}
8
問7 このログのUU(ユニークユーザー)数を表示しろ
PS > Get-Content .\input.txt| %{($_ -split ",")[2]}|Group-Object|Measure-Object|%{$_.Count}
6
問8 このログのアクセス先ごとにアクセス数を数え上位1つを表示しろ
PS > Get-Content .\input.txt| %{($_ -split ",")[3]}|group-object|sort-object -property {$_.count} -Descending | select-object -first 1|%{$_.count.tostring() + "," + $_.name}
4,/profile.php
問9 このログのserverという文字列をxxxという文字列に変え、サーバー毎のアクセス数を表示しろ
PS > Get-Content .\input.txt| %{(($_ -split ",")[0]).replace("server", "xxx")}|group-object|%{$_.count.tostring() + " " + $_.name}
3 xxx1
3 xxx2
2 xxx3
1 xxx4
問10 このログのユーザーIDが10以上の人のユニークなユーザーIDをユーザーIDでソートして表示しろ
PS > Get-Content .\input.txt| %{(($_ -split ",")[2])}|where {[int]$_ -gt 10}|sort-object {[int]$_} -unique
PS > Get-Content .\input.txt| %{(($_ -split ",")[2])}|where {[int]$_ -ge 10}|sort-object {[int]$_} -unique
12
20
30
35
複数のキーを指定してソートさせるのがなかなかうまくいかなくて悩んだ。
数値で比較して欲しいのに文字列比較するとか。