キモブロ

Please spy check please, Fucking retard

シェル操作課題 (cut, sort, uniq などで集計を行う) 解答編

これ腕試しにやってみた。
シェル操作課題 (cut, sort, uniq などで集計を行う) 設問編 - Yamashiro0217の日記

この手のワンライナー問題でsed/awk/perlとか使うのは邪道だと思ってるので一切使ってない。

まずデータ作る

$ cat > ./test.csv
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 このファイルを表示しろ

$ cat ./test.csv

問2 このファイルからサーバー名とアクセス先だけ表示しろ

$ cat ./test.csv | cut -d, -f1,4
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の行だけ表示しろ

$ fgrep 'server4' test.csv
server4,1343363225,12,/video.php

問4 このファイルの行数を表示しろ

$ wc -l ./test.csv
9 ./test.csv

問5 このファイルをサーバー名、ユーザーIDの昇順で5行だけ表示しろ

$ sort -k1,1 -k3,3n -t, ./test.csv | head -n 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 このファイルには重複行がある。重複行はまとめて数え行数を表示しろ

$ sort ./test.csv | uniq -c | wc -l
8

問7 このログのUU(ユニークユーザー)数を表示しろ

$ cat test.csv  | cut -d',' -f3 | sort | uniq -c | wc -l
6

問8 このログのアクセス先ごとにアクセス数を数え上位1つを表示しろ

$ cat test.csv | cut -d',' -f4 | sort | uniq -c | sort -nr | head -n1
      4 /profile.php

問9 このログのserverという文字列をxxxという文字列に変え、サーバー毎のアクセス数を表示しろ

$  cat test.csv  | cut -d',' -f1 | sort | uniq -c | replace server xxx
3 xxx1
3 xxx2
2 xxx3
1 xxx4

問10 このログのユーザーIDが10以上の人のユニークなユーザーIDをユーザーIDでソートして表示しろ

$ cat ./test.csv | cut -d, -f3 | grep -P '\d{2,}' | sort -n | uniq
12
20
30
35