Shell Script : Grouping and Summation

มี Log ขนาดใหญ่ แล้ว ต้องการจะวิเคราะห์ข้อมูลของนาทีที่ผ่านมา เลือกเฉพาะรูปแบบที่ต้องการด้วยคำสั่ง

grep 'Apr 28 10:59' /var/log/mail.log | grep 'postfix/qmgr' |grep 'nrcpt=' |grep -v 'from=<>'

ได้ผลมาประมาณนี้

01

ต้องการเอาข้อมูล X และ Y จากรูปแบบนี้ from=<X> และ nrcpt=Y ใช้ความรู้จาก Shell Script: Extract exact pattern from string ใช้คำสั่งต่อไปนี้

grep 'Apr 28 10:59' /var/log/mail.log | grep 'postfix/qmgr' |grep 'nrcpt=' |grep -v 'from=<>'|sed -n 's/.*\sfrom=<\(.*\)>.*\snrcpt=\(.*\)\s(.*/\1:\2/p'

ได้ผลมาประมาณนี้

02

ต้องการจับกลุ่มตาม คอลัมน์ที่ 1 แล้วหาผลรวมของคอลัมน์ที่ 2 ในแต่ละกลุ่ม ใช้คำสั่ง

grep 'Apr 28 10:59' /var/log/mail.log | grep 'postfix/qmgr' |grep 'nrcpt=' |grep -v 'from=<>'|sed -n 's/.*\sfrom=<\(.*\)>.*\snrcpt=\(.*\)\s(.*/\1:\2/p' | awk 'BEGIN{FS=OFS=":"}{a[$1]+=$2}END{ for (i in a) print i,a[i]}'

ได้ผลดังนี้

03

Reference:

http://unix.stackexchange.com/questions/169215/group-by-and-sum-in-shell-script-without-awk