Application of awk built-in Variables
Now let's look at some examples. They start with the variable NR. Modify the print statement in the script for calculating the average score:
$ Cat grades
John 85 92 78 94 88
Andrea 89 90 75 90 86
Jasper 84 88 80 92 84
$ Cat grades. awk
# Calculate the average value of five scores
{Total = $2 + $3 + $4 + $5 + $6
Avg = total/5
Print NR ".", $1, avg}
The output of the modified script is as follows:
$ Awk-f grades. awk grades
1. john 87.4
2. andrea 86
3. jasper 85.6
After the last row is read, the NR value is the number of input records read. It can be used to generate a summary report during the END process. The following is the version modified by the phonelist. awk script.
$ Cat names
John Robinson, Koren Inc., 978 4th Ave., Boston, MA 01760,696-0987
Phyllis Chapman, GVE Corp., 34 Sea Drive, Amesbury, MA 01881,879-0900
$ Cat phonelist. awk
# Phonelist. awk-print the name and phone number.
# Enter the file name, company, street, city, state, zip code, and phone number.
BEGIN {FS = ", *"} # Use commas to separate fields
{Print $1 "," $6}
END {print ""
Print NR, "records processed ."}
This program modifies the default field separator and prints the total number of records using NR. Note that this program uses a regular expression. The output result of program execution is as follows:
$ Awk-F,-f phonelist. awk names
John Robinson, 696-0987
Phyllis Chapman, 879-0900
2 records processed.
When the parameters are separated by commas in the print statement, the output field separator (OFS) is generated ). You may have questions about the functions of the comma in the following expressions:
Print NR ".", $1, avg
By default, a comma will generate a space in the output (default value of OFS ). For example, you can use the BEGIN process to redefine OFS as a tab. The preceding print statement generates the following output:
$ Awk-f grades. awk grades
1. john 87.4
2. andrea 86
3. jasper 85.6
This method is particularly useful if the input fields are separated by tabs and you want to produce the same output. OFS can be redefined as a series of characters, such as a comma followed by a space.
Another common system variable is NF, whose value is set to the number of fields in the current record. As we will see in the next section, we can use NF to test whether the number of fields in a record is the same as expected. You can also use NF to reference the last field of each record. You can use the "$" field operator and NF to implement this reference. If there are 6 fields, "$ NF" is the same as "$6.