Featured Post

Wednesday, May 11, 2016

awk command



awk is programming language as well as text processor that can be used to manipulate text data.
awk command considers the given file as data base file, each line of the file is considered as a record, each word of a line is taken as field.

awk 'BEGIN{   }
      {

      }
END{}' file name

  • In BEGIN section we write the operations what ever we want to execute before processing any record.
  • Instructions which are required to be executed on record has to be written in the middle block. 
  • The operations which are required to be executed after processing all the records has to be written in END section.
awk assumes space as the filed separator between words in a line.We can use other characters as separators using -d option.

awk have separate name for the following combination of letters.

NF=number of fields
NR=number of records
OFS=output field separator
$0=current record as a whole
$1,$2,.....=first,second,............fields of current record

awk '{print $0}' filename
 this command displays the content of the file




//awk program to check whether the student is pass or fail

awk 'BEGIN{print"\nNanme\tds\tc\tjava\ttotal\taverage\tpassoorfail"}
{
        total=0
        total=total+$2+$3+$4
        avg=total/3
        if ( $2>=35&&$3>=35&&$4>=35 )
        {
                str="pass"
        }
        else
        {
                str="fail"
        }
        print"\n"$1"\t"$2"\t"$3"\t"$4"\t"total"\t"avg"\t"str
}' pass    //note    pass is text file containing student data

output:
       Name         ds        c     java        total     average       pass or fail
        anil            60      60    60           180       60               pass
        raj              90      90     30          210       70               fail



//awk program to print student marks list

awk 'BEGIN{print"\nNanme\tds\tc\tjava\ttotal\taverage"}
{
        total=0
        total=total+$2+$3+$4
        avg=total/3
        print"\n"$1"\t"$2"\t"$3"\t"$4"\t"total"\t"avg
}' pass             //note: pass is text file which contains student data

output:
 Name        ds       c         java      total    average
  anil           90     90          60      240        80
   raj            60     70          80      210        70
   kumar      50     50          50      150        50


//count characters

awk 'BEGIN{count=0;print "CHARACTERS"}
{
  len=0
  len=length($0)
  count=count+len

}
END{print "No of characters in file are: \t"count}' sample.c  // note: sample.c is text document

Output:
 No of characters in file are 37

awk command, filters, BEGIN{}.END{},fleece , NF, NR,OFS, sample programs, awk program to print student pass/fail report, awk program to print number of vowels in a given file,awk program to print first class second class third class bases on total average marks





No comments:

Post a Comment