AWK Part-3
AWK Part-3
words.txt
storeroom
tree
cup
store
book
cloud
existence
ministerial
falcon
town
sky
top
bookworm
bookcase
war
scores.txt
Peter 89
Lucia 95
Thomas 76
Marta 67
Joe 92
Alex 78
Sophia 90
Alfred 65
Kate 46
$ awk '{sum += $2} END { printf("The average score is %.2f\n", sum/NR) }'
scores.txt
The average score is 77.56
Example 3
$ ls -l
total 132
drwxr-xr-x 2 jano7 jano7 512 Feb 11 16:02 data
-rw-r--r-- 1 jano7 jano7 110211 Oct 12 2019 sid.jpg
-rw-r--r-- 1 jano7 jano7 5 Jul 22 20:21 some.txt
-rw-r--r-- 1 jano7 jano7 226 Apr 23 16:56 thermopylae.txt
-rw-r--r-- 1 jano7 jano7 365 Aug 4 10:22 users.txt
-rw-r--r-- 1 jano7 jano7 24 Jul 21 21:03 words.txt
-rw-r--r-- 1 jano7 jano7 30 Jul 22 21:20 words2.txt
Example 4
users.txt
John Doe, gardener, London, M, 11/23/1982
Jane Doe, teacher, London, F, 10/12/1988
Peter Smith, programmer, New York, M, 9/18/2000
Joe Brown, driver, Portland, M, 1/1/1976
Jack Smith, physician, Manchester, M, 2/27/1983
Lucy Black, accountant, Birmingham, F, 5/5/1998
Martin Porto, actor, Los Angeles, M, 4/30/1967
Sofia Harris, interpreter, Budapest, F, 8/18/1993
males_females.awk
{
if ($4 ~ "M") {
m++
} else {
f++
}
}
END {
printf "users: %d\nmales: %d\nfemales: %d\n", m+f, m, f
}
Regular expressions are often applied on AWK fields. The ~ is the regular
expression match operator. It checks if a string matches the provided regular
expression.
In this command we print all the words that begin with b or c character. The
regular expression is placed between two slash characters.
The command prints all words that have three characters. The doc (.) stands
for any character and the \< \> characters are word boundaries.
We combine two condition with the or (||) operator. The AWK command
prints all words that have either three of four characters.
With the alternation operator (|), we print fields that contain either of the
specified wores.
Example 6
values.txt
2 3 1 34 21 12
43 21 11 2 11 33 12
43 72 91 90 32 14
34 87 22 12 75 2 42 13
75 23 1 42 41 94 4 32
21621314
53 13 52 84 14 14 63
3 2 5 76 31 45
$ awk 'NF == 6' values.txt
2 3 1 34 21 12
43 72 91 90 32 14
3 2 5 76 31 45
calc_sum.awk
{
for (i = 1; i<=NF; i++) {
sum += $i
}
sum = 0
}
date | awk ‘{
if($4 < 12) print ”good afternoon”
else print ”good morning” }’
B. Design a command “fags” thats will list the files and their ages, to
date.
ls –l | awk ‘BEGIN{
no [“Jan”]=1
no[“Feb”]=2
.
.
no[“Nov”]=11
no[“Dec”]=12
split(“’”`date`”’”,age)
}
{
m=no[age[2]]-no[$6]
d=age[3]-$7
if(d<0) { d=d+30;m--}
printf(“%s ➔ mon %d:%d\n”,$9,m,d)
}’