Tag: awk

  • 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

  • How to list linux file permissions in Octal Notation

    วันนี้เนื่องจากทีมผู้ดูแล  Web Hosting ต้องการดูว่ามีไฟล์ไหนบ้างที่มี permission เป็น 777 ก็เลยนั่งหาดูพบว่า สามารถใช้คำสั่ง stat ในการดูได้ เช่น

    $stat -c "%a %n" /var/www

    ผลลัพธ์
    Screenshot from 2013-05-01 11:47:06

    หรือ

    $stat -c "%A (%a) %8s %.19y %n" /var/www

    ผลลัพธ์
    Screenshot from 2013-05-01 11:49:19

    ทั้งนี้เนื่องจากไม่สามารถทำให้มัน recursive ได้ ก็ต้องหาไปทีละโฟลเดอร์ …. จนกระทั่งเจออีกคำสั่ง คือ สร้าง alias ชื่อ lso ดังนี้

    $alias lso="ls -alG | awk '{k=0;for(i=0;i<=8;i++)k+=((substr(\$1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf(\" %0o \",k);print}'"

    เมื่อจะใช้งาน ก็เพียงสั่ง lso ที่คอมมานด์ไลน์ ผลลัพธ์
    Screenshot from 2013-05-01 11:54:27

    สามารถปรับ option ของ ls ใน alias ให้ recursive ได้โดยเพิ่ม R ตัวใหญ่ลงไป ดังนี้

    $alias lso="ls -alGR | awk '{k=0;for(i=0;i<=8;i++)k+=((substr(\$1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf(\" %0o \",k);print}'"

    เมื่อเรียกใช้จะได้ผลลัพธ์
    Screenshot from 2013-05-01 11:57:21

    สามารถใช้ร่วมกับ grep เพื่อค้นหาเฉพาะค่าที่ต้องการ เช่น

    $lso|grep " ^777"

    ผลลัพธ์
    Screenshot from 2013-05-01 13:11:12

    ก็พอจะช่วยได้บ้างครับ Big Smile ขอให้สนุกครับ

    ที่มา

    http://thenubbyadmin.com/2012/02/16/how-to-list-linux-file-permissions-in-octal-notation/

    http://askubuntu.com/questions/152001/how-can-i-get-octal-file-permissions-from-command-line