AWK scripting: What is an AWK and how to use it?
AWK scripting: 14 AWK print statment examples
AWK scripting: 8 AWK printf statements examples
AWK scripting: 10 BEGIN and END block examples
What is a Variable?
A variable is defined as storage location to store some value in it so that we can use this in a program. Variables will protect us from varying values in the storage location. This will help us to avoid hardcode a value in to program where ever it’s used. We can define a variable at the start of program and use the variable across the program, if we want to change the value of it, we can change it where we define it and this value will be updated where ever we use that variable.
Defining a variable in AWK
We can define variable in AWK where ever we require. Variables can be used for
Initializations for values
Arithmetic operations
And many more.
For this concept we will use below db.txt file.
cat db.txt
Jones 2143 78 84 77
Gondrol 2321 56 58 45
RinRao 2122234 38 37
Edwin 253734 87 97 95
Dayan 24155 30 47
Lets learn AWK variables with examples
Example1: Add all values in column 3 and display for each addition from our db.txt file. Frist value should be first value in column3, second in the list should be first value + second value and so on.
awk ‘BEGIN{a=0}{a=a+$3;print a}’ db.txt
Output:
78
134
172
259
289
In the above example we defined a variable a and initialized to zero in the BEGIN block and did arithmetic operation in main block.
Example2: I don’t want above output, I just want to print a final value once the sum of all value in 3rd column. We can use END block for doing a final print instead of printing per iteration.
awk ‘BEGIN{a=0}{a=a+$3}END{print a}’ db.txt
Output:
289
Example3: Print all the lines which contain numbers greater than VAR1 in it’s column 4
awk ‘BEGIN{VAR1=57}(VAR1<$4){print $0}’ db.txt
Output:
Jones 2143 78 84 77
Gondrol 2321 56 58 45
Edwin 253734 87 97 95
These are simple examples to start with Varaiables. In our next post we will see how get inputs from user.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020 - FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018