awk Programming awk has several functions already built-in for string and numeric operations. Here are some of the most common, and ones I'm familiar with. Others are available if you wish to pursue that option.
awk 'BEGIN {sum=22.55; print int(sum) }'
22awk 'BEGIN {sum=25; print sqrt(sum) }'
5awk 'BEGIN {sum=3; print exp(sum) }'
20.0855Note: e is the base of natural logarithms: 2.7182818284...awk 'BEGIN {sum=10; print log(10) }'
2.30259awk 'BEGIN {sum=30; print sin(sum) }'
-0.988032awk 'BEGIN {sum=30; print cos(sum) }'
0.154251awk 'BEGIN { angle=atan2(1,2);print angle }'
0.463648awk 'BEGIN { guess=rand();print guess }'
0.840188Note: rand generates from the same seed, thus repeated execution of a script produces the same result. Use srand to change the seed.awk 'BEGIN {srand(100); {print rand() i++}}'
0.3155980If the x argument is left out, the seed is the current date and time of day. Use this for more 'random' numbers.CAUTION: A number of functions deal with indices into strings. For these functions, the first character of a string is at position (index) one. This is different from C and the languages descended from it, where the first character is at position zero. You need to remember this when doing index calculations, particularly if you are used to C.
awk 'BEGIN {print index("discombobulation","u")}'
10awk 'BEGIN {print length("discombobulation")}'
16
awk 'BEGIN {print length(2587946130)}'
10
awk 'BEGIN {print length(25 * 2)}'
2
awk 'BEGIN {print length(25 * 10 + 1)}'
3
awk 'BEGIN{print length (12345) + 1}'
6
awk 'BEGIN{n=split("You-are-here!",a,"-");
print "Array contains " n " elements";
print "Third element: "a[3]}'
Array contains 3 elements:
Third element: are
Field separators can be multiple characters
awk 'BEGIN{n=split("You.:.are.:.here!",a,".:.");
print "Array contains " n " elements:\n";
print a[1]a[2]a[3]
print "Third element: "a[3]"\n"}
Array contains 3 elements:
Youarehere!
Third element: here!
You can also pipe a string into awk like this:
echo "12|23|11" | awk '{split($0,a,"|"); print a[3],a[2],a[1]}'
11 23 12
See also Stack Overflow and POFTUT.These patterns supply startup and cleanup actions but there is no default action since there is no current record when they run.
awk 'BEGIN {FS=":"}; {print NF }' names.txt
2
2
2
2
2
2
awk 'END {print FNR}' names.txt
6