Thursday, September 13, 2012

AWK - Unix

What is AWK ?


Scans a set of input lines, searching for lines that match any set of patterns and take a specified action for each pattern on each line that matches the pattern


 Usage


awk ‘pattern-action statements’ optional list of input files
e.g. awk ‘{print $1, $2}’ file1 file2
OR
awk -f programfile optional list of input files
where programfile is the file where the pattern-action statements are stored


 Fields

Record is the sequence of characters separated by a newline character
Fields in a record are separated by sequence of blanks or tabs
$0 refers to the entire record
$1 refers to the first field
$2 refers to the second field


Printing

{ print }
prints all the records
{print $1 $3}
prints the first and third fields of each of the input line



BuiltIn Variables
ARGC  number of command line arguments
ARGV  array of command line arguments
FILENAME  name of current input file
FNR  record number in current file
NR   number of current record
NF  number of fields in the record
OFS  Output field separator
ORS  Output record separator

 Examples
Print last field of each input line

{ print $NF }
Print total number of input lines
END {print NR}
Print input lines with more than 4 fields
NF > 4
Print the total no of lines that match string “abc
/abc/  {nlines++} END {print nlines}


cos(x)

log(x)
exp(x)
rand(x)
sin(x)
sqrt(x)
srand(x)

BuiltIn String Functions
index(s,t)  returns position of t in s
length(s)  returns length of s
split(s,a)  splits into array a on FS
sub(s,r)  substitutes s for first r
substr(s,p)  returns suffix of string starting at position p

Control Flow Statements
if (expression) stat1 else stat2
while (expression) stat
for (expr1;expr2;expr3) stat
do stat while (expr)
break
continue
next
exit(expr)
return(expr)

Example scenarios

No comments:

Post a Comment

Hyderabad Trip - Best Places to visit

 Best Places to Visit  in Hyderabad 1.        1. Golconda Fort Maps Link :   https://www.google.com/maps/dir/Aparna+Serene+Park,+Masj...