LINUX AWK Tutorial Series | Chapter 11
In this post, I am going to share the functions in AWK.
Functions in AWK can be built-in functions and user-defined functions
Built-In Functions: These are pre-defined functions that are already available. We can directly call and use them.
Let's see some of them
sqrt(x): positive square root of a number x
init(x): Truncate x to an integer value for any positive and negative number.
exp(x): Gives exponential of x
rand(): it returns any random value between 0 and 1. But will not return 0 or 1. It will random in one awk execution.
srand(x): Provide seed value of x random function. if x is not present date and time is used as an seed value.
length(x) : Length of particular string
index(s1,s2): Position of a string s2 in larger string s1.
substr(s,a,b): Extract a substring from larger string s. a is the index position to start reading and b is the total characters to be read starting from position a.
system(): Run unix command within AWK
We can see many arithmetic functions, I will not mention all but a few more which you can look out for is log(x), sin(x), cos(X)
Example 1:
Let's perform the basic operations
Example 2:
Random number generation. If you observe I have used the rand() and srand() function to generate random numbers.
[himanshu@oel7 AWK]$ cat random_funtion BEGIN{ srand() print rand() } [himanshu@oel7 AWK]$ awk -f random_funtion 0.0376296
Try at Home: If you remove srand from the above script file what will happen.
Example 3:
Using a string function.
[himanshu@oel7 AWK]$ cat string_function BEGIN{ print length("Himanshu"); print index("Himanshu","man") } [himanshu@oel7 AWK]$ awk -f string_function 8 3
Example 4:
Display date using AWK.
[himanshu@oel7 AWK]$ awk 'BEGIN{system("date")}' Thr Nov 5 07:28:49 IST 2020
Next chapter I will tell how to create user-defined function in AWK.
Post a Comment
Post a Comment