awk tutorial: Learn about awk variables with 3 practical examples
This article is a part of the ongoing series of Awk tutorials and examples. Like any other programming language, Awk also has user-defined variables and built-in variables.
In this article, let's review how to define and use awk variables.
Awk variables should start with a letter and can contain alphanumeric characters or underscores. Keywords cannot be used as awk variables. Awk does not support variable declaration like other programming languages. It is always better to initialize awk variables in the BEGIN section, which is executed only once at the beginning. There are no data types in awk. Whether an awk variable is treated as a number or a string depends on the context in which it is used. Now let us review a few simple examples to learn how to use user defined awk variables.
awk example 1: book billing
In this example, the input file bookdetails.txt contains records with fields - item number, book name, quantity, and price of each book.
$ cat bookdetails.txt
Now the following Awk script reads and processes the above bookdetails.txt file and generates a report showing - the sales rate of each book, and the total amount of all the books sold.
So far, we have seen Awk read commands from the command line, but Awk can also read commands from a file using the -f option.
语法
$ awk -f script-filename inputfilename
Now our Awk script for book billing calculations looks like this.
$ cat book-calculation.awk
BEGIN {
total=0;
}
{
itemno=$1;
book=$2;
bookamount=$3*$4;
total=total+bookamount;
print itemno," ", book,"\t","$"bookamount;
}
END {
print "Total Amount = $"total;
}
In the above script,
- The awk BEGIN section initializes the variable total. itemno, total, book, bookamount are user-defined awk variables.
-
In the Awk Action section,
Quantity*bookprice
this will be stored in a variable called bookamount. Each book amount will be added to the total. - Finally in the Awk END section, the total variable will have the total amount.
Now execute the book-calculation.awk script to generate a report showing each book rate and total amount as shown below.
$ awk -f book-calculation.awk bookdetails.txt
awk example 2. Student score calculation
In this example, an input file "student-marks.txt" is created which contains the following contents - Student Name, Roll Number, Test1 Marks, Test2 Marks and Test3 Marks.
$ cat student-marks.txt
Now, the following awk script will calculate and generate a report to show the average score of each student, the average of Test1, Test2 and Test3 scores.
student.awk
BEGIN { test1=0; test2=0; test3=0; print "Name\tRollNo\t Average Score"; } { total=$3+$4+$5; test1=test1+$3; test2=test2+$4; test3=test3+$5; print $1"\t"$2"\t",total/3; } END{ print "Average of Test1="test1/NR; print "Average of Test2="test2/NR; print "Average of Test3="test3/NR; }
In the above awk script,
- In the Awk BEGIN section, all awk variables are initialized to zero. test1, test2, test3, and total are user defined awk variables.
- In the Awk ACTION section, $3, $4, $5 are the scores of Test1, Test2, and Test3 respectively. The total variable is the sum of the 3 test scores for each student. The awk variables test1, test2, and test3 have the total score for each corresponding test.
- So, in the Awk END section, dividing each test total by the total number of records (i.e. students) will give us the average score. NR is an Awk inbuilt variable which gives the total number of records in the input.
awk example 3. HTML report of student details
In above two examples, we have seen awk variables whose values are numbers. This example shows awk script to generate html report for student names and their roll numbers.
string.awk
BEGIN{ title="AWK"; print "<html>\n<title>"title"</title><body bgcolor="#ffffff">\n<table border=1><th colspan=2 align=centre>Student Details</th>"; } { name=$1; rollno=$2; print "<tr><td>"name"</td><td>"rollno"</td></tr>"; } END { print "</table></body>\n</html>"; }
Use the same student-marks.txt input file that we created in the example above .
$ awk -f string.awk student-marks.txt
We can store the above output which gives the following html table. In the above script, the variables named name and rollno are string variables as it is used in string context.
Student | Details |
---|---|
Jones | 2143 |
Gondrol | 2321 |
RinRao | 2122 |
Edwin | 2537 |
Dayan | 2415 |
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
How to decompress x.tar.xz format files under Linux
Publish Date:2025/04/08 Views:186 Category:OPERATING SYSTEM
-
A lot of software found today is in the tar.xz format, which is a lossless data compression file format that uses the LZMA compression algorithm. Like gzip and bzip2, it supports multiple file compression, but the convention is not to compr
Summary of vim common commands
Publish Date:2025/04/08 Views:115 Category:OPERATING SYSTEM
-
In Linux, the best editor should be vim. However, the complex commands behind vim's powerful functions also make us daunted. Of course, these commands do not need to be memorized by rote. As long as you practice using vim more, you can reme
Detailed explanation of command return value $? in Linux
Publish Date:2025/04/08 Views:58 Category:OPERATING SYSTEM
-
? is a special variable. This variable represents the return value of the previous command. That is to say, when we run certain commands, these commands will return a code after running. Generally, if the command is successfully run, the re
Common judgment formulas for Linux script shell
Publish Date:2025/04/08 Views:159 Category:OPERATING SYSTEM
-
In shell script programming, predicates are often used. There are two ways to use predicates, one is to use test, and the other is to use []. Let's take a look at how to use these two methods through two simple examples. Example 1 # test –
Shell script programming practice - specify a directory to delete files
Publish Date:2025/04/08 Views:98 Category:OPERATING SYSTEM
-
Usually, in Linux system we need to frequently delete some temporary files or junk files. If we delete them one by one manually, it will be quite troublesome. I have also been learning shell script programming recently, so I tried to write
Use of Linux command at - set time to execute command only once
Publish Date:2025/04/08 Views:158 Category:OPERATING SYSTEM
-
This article mainly involves a knowledge point, which is the atd service. Similar to this service is the crond service. The functions of these two services can be similar to the two functional functions of javascript. Those who have learned
Use of Linux command crontab - loop execution of set commands
Publish Date:2025/04/08 Views:170 Category:OPERATING SYSTEM
-
Compared with at , which executes a command only once, crontab, which we are going to talk about in this article, executes the set commands in a loop. Similarly, the use of crontab requires the support of the crond service. The service is s
Linux practice - regularly delete files under the directory
Publish Date:2025/04/08 Views:198 Category:OPERATING SYSTEM
-
Since we want to delete the files under the directory regularly, we need to use the Linux crontab command. And the content format of each work routine is also introduced in the format of each crontab work. Similarly, we need to use shell sc
How to use the Linux file remote copy command scp
Publish Date:2025/04/08 Views:151 Category:OPERATING SYSTEM
-
Scp copies files between two hosts over the network, and the data is encrypted during transmission. Its underlying layer uses ssh for data transmission. And it has the same authentication mechanism and the same security level as ssh. When u