Tag: sed

  • 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

  • Shell Script : Extract exact pattern from string

    มี string ดังนี้ ในตัวแปร line

    line=’Apr 18 06:04:57 webmail squirrelmail: Message sent via webmail: by username.s (psu.ac.th) at 41.203.69.5 on 04/17/2015 23:04:57: Message-ID: 98f9739438686e127bcb8547fea7ed82.squirrel@webmail.psu.ac.th Total 9 recipients Message-ID: 98f9739438686e127bcb8547fea7ed82.squirrel@webmail.psu.ac.th’

    ต้องการค่าที่อยู่ระหว่าง Total … recipients

    ใช้คำสั่งนี้

    total=$(echo $line | sed -n ‘s/.*Total \([[:digit:]]*\) recipients.*/\1/p’)

    ตัวแปร $total จะมีค่า 9 ตามที่ต้องการ

    อธิบาย
    คำสั่ง
    sed -n ‘s/PATTERN/&/p’
    จะแสดงข้อความที่ตรงกับ Pattern เท่านั้น ไม่แสดงข้อความอย่างอื่่น

    Reference:
    http://www.grymoire.com/Unix/Sed.html#uh-15