Thursday 25 April 2013

AWK Examples

1) An awk script which performs arithmetic.

awk '{

x = 3; y = 3;

print ($1/7) + ($2 - y)/x

z = $2 - 4;

print z

}'   file_1.txt

2) awk script to print the  filename  and its size and  finally total size occupied by all files.

ls -lrt | awk 'BEGIN { c = 0; siz = 0;print FILENAME BYTES}

NF == 9 && /^-/

{

print $9 " " $5;c++;siz += $5

}

END{

print "\nTOTAL COUNT = " c "\nTOTAL SIZE = " siz

}' 



3) consider a file(name_addr.txt)  containing names and addresses with records seperated by a blank line and fields seperated by newline.

kaushik

nayak

dl hsg socty

vashi

jose

dmello

ms clny

blore

reema

j l

highway rd

seattle

awk command to extract only first name from this file will be

awk 'BEGIN{FS ="\n";RS=""}

{

print $1

}' name_addr.txt


4)awk command to count the total number of blank lines in a file.

awk ' /^$/

BEGIN{ c = 0}

{

print x += 1

}

END

{

print c

}'  file_cont_blkline.txt


5) An awk script to count the total number of occurences of a pattern.

awk -v ptr=0003  'BEGIN{c = 0}{c += gsub(ptr," ",$0) }END{print c} ' sql2.txt

#here the pattern to count is '0003'  whose value is passed through variable ptr.

6) An awk program to split output of netstat command into IP and port for a specific port .

netstat  -an | awk '$4 ~ /.1521$/ {split($5,arr1,".");print "IP = " arr1[1]"."arr1[2]"."arr1[3]"."arr1[4] "|PORT = "arr1[5]}'

7) an awk program to print lines between two patterns (pattern ZO and a blank line)
awk '$0 ~ /ZO/,/^$/{ print $0}' select_all_bRS.txt

8)An awk program to write conditional output  to multiple files .
awk '{ if ($1 ~ /2013/ ){ print $0 > "date.txt"} else if ( $3 ~ /Branch/ ) {print $0  >"brch.txt"} }' branch_dt.txt

9) An awk script showing the use of next.
awk '$1 == "20130426" && $7 == "04060" && substr($2,1,2) == 10  {printf( "%s diff = %d \n",$0,$4 - $2);next }{print}' level_2.txt
#if next is not used then $0 will again be printed by  {print}.next skips the record