Farid Ahmadian / Scripts

awk by examples

Example 1


    awk '{
        total=$2+$3+$4;
        avg=total/3;
        if(avg >= 80) grade="A";
        else if(avg >= 60) grade="B";
        else if(avg >= 50) grade="C";
        else grade="D";
        if (grade == "A" || grade == "B")
            print $0,":",grade;
        else
            print $0,": FAIL";      
    }'

Sample Input

    A 25 27 50
    B 35 37 75
    C 75 78 80
    D 99 88 76

Sample Output

    A 25 27 50 : FAIL
    B 35 37 75 : FAIL
    C 75 78 80 : B
    D 99 88 76 : A

Example 2


    awk 'ORS=!(NR%2)?"\n":";"'

Sample Input

    A 25 27 50
    B 35 37 75
    C 75 78 80
    D 99 88 76

Sample Output

    A 25 27 50;B 35 37 75
    C 75 78 80;D 99 88 76

Example 3


    awk '{
            if ($2 >= 50 && $3 >= 50 && $4 >= 50)
                    print $1,": Pass";
            else
                    print $1,": Fail";      
    }'

Sample Input

    A 25 27 50
    B 35 37 75
    C 75 78 80
    D 99 88 76

Sample Output

    A : Fail
    B : Fail
    C : Pass
    D : Pass

Example 4


    awk '{
            if($2=="" || $3=="" || $4=="")
                    print "Not all scores are available for "$1
    }'

Sample Input

    A 25 27 50
    B 35 75
    C 75 78 
    D 99 88 76

Sample Output

    Not all scores are available for B
    Not all scores are available for C

BY: Farid Ahmadian
TAG: awk
DATE: 2020-06-02 18:36:39


Farid Ahmadian / Scripts [ TXT ]

With many thanks and best wishes for dear Pejman Moghadam, someone who taught me alot in linux and life :)