You are on page 1of 2

*AWK

Filtering, input file can be processed,


data can be manipulated, arithmetic operations, string operations

Syntax:

1)awk [option] filename

2)awk 'BEGIN {actions} {awk command/actions} END{actions}' filename

FS - Field Seperator
OFS - Output Field Seperator
NR - Number of Records
NF - Number of Fields
RS - Record Seperator
ORS - Output Record Seprator

1) awk '/pattern/' filename #Displays the complete record matching the pattern

2) awk '/pattern1|pattern2/' filename #Displays the complete record matching both


the patters

emp_name,age,city,exp,salary

1) awk -F "," '{print $1,$2}' employee.dat


#Prints the first two fields of the file

2) awk '/pattern|pattern2/' employee.dat


#Prints the details of employees matching the pattern

3) awk -F "," 'BEGIN{s=0}{s=s+$5}END{print "The total salary is",s}' employee.dat


#Finds the total salary of all the employees and prints

4) awk '/10000/{++count} END{print "Count is",count}' employee.dat


#Prints the number of employees whose salary is more than 10000

5) Performance Report

awk 'BEGIN {print "Performance Report"}{FS=OFS=","}


{if($4==2 && $5>10000) {print $1 "is a good performer"}
else if($4==2 && $5<=10000)
{print $1 "needs improvement"}}
END {print "Ends here"}' employee.dat
#To generate performance report of employees

6) c_id|c_name|age|city|email

awk -F "|" '{print $2,$4,$5}' cust.txt

awk file:(custawk.awk)
#!/usr/bin/awk -f
{BEGIN FS=OFS="|"}
{print $2,$4,$5}

txt file:(cust.txt)
c_id|c_name|age|city|email
to run the awk command

# awk -F "|" -f custawk.awk cust.txt

or

./custawk.awk cust.txt

6.1)To find the average age of the customers

#!/usr/bin/awk -f
{BEGIN FS="|" sum=0}
{sum=sum+$3;}
END{print "Avg Age" sum/NR;}

6.2) to print the name of customers having gmail account

#!usr/bin/awk -f
BEGIN{FS="|"}
{if(index($5,"gmail")>0)
{
print $2 "\t" $5
}
}

You might also like