Day: April 21, 2015

  • 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