© Rochak Sachan
awk utility is powerful data manipulation/scripting programming language
Based on the c programming language
Use awk to handle complex task such as calculation, database handling, report creation etc.
2
awk utility
© Rochak Sachan 3
awk metacharacters
Pattern { action 1
action 2
action N
}
Syntax: awk -f {awk program file} {DATAfilename}
awk Program contains are something as follows:
© Rochak Sachan
awk reads the input from given file (or from stdin also) one line at a
time, then each line is compared with pattern.
If pattern is match for each line then given action is taken. Pattern
can be regular expressions.
Following is the summery of common awk metacharacters:
Metacharacter Meaning
. (Dot) Match any character
* Match zero or more character
^ Match beginning of line
$ Match end of line
\ Escape character following
[ ] List
{ } Match range of instance
+ Match one more preceding
? Match zero or one preceding
| Separate choices to match
© Rochak Sachan
1 Pen 5 20.00
2 Rubber 10 2.00
3 Pencil 3 3.50
4 Cock 2 45.50 ISHQ
Create a file name inven using your favourite editor like this
© Rochak Sachan
awk '{ print $1 $2 "--> KRW." $3 * $4} ‘ > TEMP.TXT
awk '{ print $2 }' inven
awk '{ print $0 }' inven
Now try this following commands one by one.
© Rochak Sachan
Our next example talks more about predefined variable of awk. Create awk file
as follows:
$cat > def_var
{
print "Printing Rec. #" NR "(" $0 "),And # of field for this record is
" NF
}
Run it as follows.
$awk -f def_var inven
© Rochak Sachan
Run the awk program as follows: $ awk -f math 56 45
(Press CTRL + D to terminate)
8
Doing arithmetic with awk
$ cat > math
{
print $1 " + " $2 " = " $1 + $2
print $1 " - " $2 " = " $1 - $2
print $1 " / " $2 " = " $1 / $2
print $1 " x " $2 " = " $1 * $2
print $1 " mod " $2 " = " $1 % $2
}
© Rochak Sachan
Run the program as follows $ awk -f math1
1 5
output : 1 + 5 = 6
9
User Defined variables in awk
$ cat > math1
{
no1 = $1
no2 = $2
ans = $1 + $2
print no1 " + " no2 " = " ans
}
© Rochak Sachan
cat > bill
{
total = $3 * $4
recno = $1
item = $2
Print recno item " KRW." total
}
awk '{ print $1 $2 "--> KRW." $3 * $4} ‘ inven
$ awk -f bill inven
1 Pen 5 20.00
2 Rubber 10 2.00
3 Pencil 3 3.50
4 Cock 2 45.50 ISHQ
EQUIVQLENT PROGRAMME USING USER DEFINED VARIABLE
© Rochak Sachan
1 PEN RED
2 PAPER RED
3 PENCIL YELLOW
4 RUBBER RED
Print the records having RED color using awk command. Use ‘/string/{print $no}’
Create a table like the following
© Rochak Sachan
ANS IS : awk ‘/RED/’{print $0}’ <table_file_name>
You should see row 1 2 and 4 in output.
© Rochak Sachan
1. Richard Petersen; "The Complete Reference, Linux, Fourth Edition", Osbor
ne/McGraw-Hill
2. Christopher Negus; "Linux Bible, 2007 Edition", Wiley Publishing, Inc.
3. http://www.freeos.com/guides/lsst/
4. http://bash.cyberciti.biz/guide/Main_Page
References
References