Skip to content

05.Easy tricks *

This exercise will illustrate another convenient feature of Awk - generating data from simple functions, simple list or even some more advanced data sets which does not require files to read/analyse. If you use only the BEGIN block, awk will not try to read any file. One can simply write, which will simply print to the terminal:

$ awk 'BEGIN{print "Hello, world!"}'
Hello, world!

Task 1.

a) print numbers from 1 to 7 i.e. produce such output

1
2
3
4
5
6
7
Solution...
$ awk 'BEGIN{ for(i=1;i<=7;i=i+1) print i }'

b) print the same numbers on a single line i.e.

1 2 3 4 5 6 7
Solution...

Note that here we use printf which does not print the new line.

$ awk 'BEGIN{ for(i=1; i<=7; i=i+1) printf i" "}'

c) print the numbers from 1 to 7 in reverse order

d) print every other number from 1 to 7 i.e.

1
3
5
7

e) print the numbers from 1 to 2 with increments of 0.1 i.e

1
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
2
Solution...

$ awk 'BEGIN{ for(i=1; i<=2.01; i=i+0.1) print i}'
Yes, Awk allow for fractional increments... Note the upper limit 2.01!

f) can you add on each line the square of the number, exp(), sin() /the argument is in radians, don't worry/

1 1 2.71828 0.841471
1.1 1.21 3.00417 0.891207
1.2 1.44 3.32012 0.932039
1.3 1.69 3.6693 0.963558
1.4 1.96 4.0552 0.98545
1.5 2.25 4.48169 0.997495
1.6 2.56 4.95303 0.999574
1.7 2.89 5.47395 0.991665
1.8 3.24 6.04965 0.973848
1.9 3.61 6.68589 0.9463
2 4 7.38906 0.909297
Solution...
$ awk 'BEGIN{ for(i=1.; i<=2.01; i=i+0.1) print i,i**2,exp(i),sin(i)}'

g) make awk script that prints such output i.e. 2 students in each group. (**)

Group1 => Student1, Student2
Group2 => Student3, Student4
Group3 => Student5, Student6
Group4 => Student7, Student8
Group5 => Student9, Student10
Group6 => Student11, Student12
Group7 => Student13, Student14
Solution...
$ awk 'BEGIN{ for(i=1;i<=7;i++) print "Group"i" => Student"(i-1)*2+1", Student"(i-1)*2+2 }'

solution suggested by Ageo Meier de Andrade

$ awk 'BEGIN{f=1;for (i=1; i<=7; i++){print "Group"i" => Student"f++",Student"f++}}'