Thursday, September 30, 2010

awk examples

data file employee.txt
100  Thomas  Manager    Sales       $5,000
200  Jason   Developer  Technology  $5,500
300  Sanjay  Sysadmin   Technology  $7,000
400  Nisha   Manager    Marketing   $9,500
500  Randy   DBA        Technology  $6,000

awk '{print;}' employee.txt
awk '/Thomas/
 /Nisha/' employee.txt
awk '{print $2,$5;}' employee.txt
awk '{print $2,$NF;}' employee.txt
awk 'BEGIN {print "Name \tDesignation\tDepartment\tSalary";}
 {print $2,"\t",$3,"   \t",$4,"   \t",$NF;}
 END{print "Report Generated\n--------------";
 }' employee.txt
awk '$1 >200' employee.txt
# compare variable with string using ~
awk '$4 ~/Technology/' employee.txt
awk 'BEGIN { count=0;}
$4 ~ /Technology/ { count++; }
END { print "Number of employees in Technology Dept =",count;}' employee.txt

data file: bookdetails.txt
1 Linux-programming 2 450
2 Advanced-Linux 3 300
3 Computer-Networks 4 400
4 OOAD&UML 3 450
5 Java2 5 200
awk code file: book-calculation.awk

BEGIN {
    total=0;
}
{
    itemno=$1;
    book=$2;
    bookamount=$3*$4;
    total=total+bookamount;
    print itemno," ", book,"\t","$"bookamount;
}
END {
    print "Total Amount = $"total;
}

awk -f book-calculation.awk bookdetails.txt

data file: student-marks.txt
Jones 2143 78 84 77
Gondrol 2321 56 58 45
RinRao 2122 38 37 65
Edwin 2537 78 67 45
Dayan 2415 30 47 20

awk code: student.awk

BEGIN {
    test1=0;
    test2=0;
    test3=0;
    print "Name\tRollNo\t Average Score";
}
{
    total=$3+$4+$5;
    test1=test1+$3;
    test2=test2+$4;
    test3=test3+$5;
    print $1"\t"$2"\t",total/3;
}
END{
    print "Average of Test1="test1/NR;
    print "Average of Test2="test2/NR;
    print "Average of Test3="test3/NR;
}

awk code to generate HTML file: student-html.awk


BEGIN{
title="AWK";
print "\n"title"\n
Student Details"; } { name=$1; rollno=$2; avg=($3+$4+$5)/3; print " "; } END {     print "
"name""rollno""avg"
\n";
}

Ksh execute profile

For ksh at some UNIX machine, the profile is ~/.profile instead of .zshrc

Instead of execute the profile immediately by `source ~/.profile`, some system use command like

. ~/.profile

Friday, September 10, 2010

New gnome-terminal do not have the environment variables

If you want your new configuration be used in your new terminal, for example, gnome-terminal, you need to check the configuration of your terminal. In gnome-terminal, from menu of "edit" -> "Current profile", at the "title and command' tab, check "Run command as a login shell".