Skip to content
ImagineWorld

Using awk – Part 2

node_idnode-book_the-ultimate-linux-shell-scripting-guide_chapter-15-using-awk-part-2
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num15
chapter_titleUsing awk – Part 2
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, we’ll continue the discussion about awk, but from a different perspective. In the previous chapter, I showed you the basics of creating one-line awk commands that you can use in your normal shell scripts. In this chapter, I’ll show you a bit about how to write awk scripts in the awk language.

Topics in this chapter include:

  • Basic awk script construction
  • Using conditional statements
  • Using a while construct and setting variables
  • Using for loops and arrays
  • Using floating point math and printf
  • Working with multi-line records

If you’re ready, let’s dig in.

Technical Requirements

You can use either a Fedora or Debian virtual machine for this. And, as always, you can grab the scripts by doing:

git clone https://github.com/PacktPublishing/The-Ultimate-Linux-Shell-Scripting-Guide.git

Basic awk Script Construction

Let’s begin with the simplest awk script that you can imagine, which we’ll call awk_kernel11.awk. It looks like this:

/kernel/

As you’ve likely guessed, this script will look through a specified file to search for all lines that contain the text string kernel. You already know that {print $0} is the default action if no action is specified. So, this script will print out every line that contains the specified text string.

In actual awk scripts, there’s no need to preface every command with awk, and there’s no need to surround the commands with pairs of single quotes, as you have to do when embedding awk commands in normal shell scripts. I didn’t put a shebang line into this script, so there’s no need to set the executable permission. Instead, just invoke the script like this:

Terminal window
donnie@fedora:~$ sudo awk -f awk_kernel1.awk /var/log/messages
Jan 11 16:17:55 fedora kernel: audit: type=1334 audit(1705007875.578:35): prog-id=60 op=LOAD
Jan 11 16:18:00 fedora kernel: msr: Write to unrecognized MSR 0x17f by mcelog (pid: 856).
Jan 11 16:18:00 fedora kernel: msr: See https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git/about for details.
...
...
Jan 11 17:15:28 fedora kernel: fwupdmg[1779]: memfd_create() called without MFD_EXEC or MFD_NOEXEC_SEAL set
donnie@fedora:~$

Sure, that works. But, wouldn’t you really rather have a stand-alone, executable script? That’s easy enough to do. Just add the shebang line, like this:

#!/usr/bin/awk -f
/kernel/

Then, make the script executable, the same as you would do with normal bash scripts.

There are two things that I want you to notice about this shebang line. First, is that I’m using /usr/bin/ instead of /bin/ as the path to the awk executable. That’s because I want to make this script portable, so that it will run on Linux, Unix, and Unix-like systems such as FreeBSD and macOS.

The /bin/ path that you’re used to seeing in shebang lines is an artifact that’s been carried over from older Linux systems. On current Linux systems, /bin/ is a symbolic link that points to /usr/bin/. On older Linux systems, /bin/ and /usr/bin/ used to be two separate directories, which each contained two separate sets of program files. That’s no longer the case. Nowadays, you’ll find the awk executable in /usr/bin/ on all Linux systems.

FreeBSD still uses separate /bin/ and /usr/bin/ directories with different sets of program files. But, awk is in /usr/bin/, and there’s no symbolic link for it in /bin/. So, just use #!/usr/bin/awk, and you’ll be good-to-go for most operating systems.

The second thing to notice is that I still have to invoke awk with the -f option, which causes awk to read the program file. If you leave out the -f, the script won’t work.

Now that you’ve seen the basic structure of an awk script, let’s look at some awk programming constructs.

Using Conditional Statements

You’ve already been using if constructs without even knowing it. That’s because you don’t have to explicitly declare them as such. The simple /kernel/ command that you just saw in the awk_kernel1.awk script means that if the kernel string is found on a line, then print that line. However, awk also offers the whole array of programming constructs that you would expect to see in other languages. For example, let’s create the awk_kernel2.awk script, which will look like this:

#!/usr/bin/awk -f
{
if (/kernel/) {
print $0
}
}

This is somewhat different from what you’re used to seeing in bash scripts, because in awk there’s no need to use then or fi statements. This is because awk uses C language syntax for its programming constructs. So, if you’re used to programming in C, rejoice!

Also, note how you need to surround the pattern with a pair of parentheses, and how you have to surround the entire multi-line script with a pair of curly braces. At any rate, just specify the name and location of your log file when running the script, like this:

Terminal window
donnie@fedora:~$ sudo ./awk_kernel2.awk /var/log/messages

Now, you’re probably wondering why anyone would want to do the extra typing to create a full-blown if construct when just typing /kernel/ will do the job. Well, it’s so that you can create full-blown if..else constructs, like this one in the awk_kernel3.awk script:

#!/usr/bin/awk -f
{
if ($5 ~ /kernel/) {
print "Kernel here in Field 5"
}
else if ($5 ~ /systemd/) {
print "Systemd here in Field 5"
}
else {
print "No kernel or systemd in Field 5"
}
}

Now, let’s see how many times each type of message shows up in the log file:

Terminal window
donnie@fedora:~$ sudo ./awk_kernel3.awk /var/log/messages | sort | uniq -c
25795 Kernel here in Field 5
38580 No kernel or systemd in Field 5
35506 Systemd here in Field 5
donnie@fedora:~$

Cool, it works.

For our final if trick, let’s create the awk_kernel14.awk script, like this:

#!/usr/bin/awk -f
{
if ($5 ~ /kernel/) {
print "Kernel here in Field 5 on line " NR
}
else if ($5 ~ /systemd/) {
print "Systemd here in Field 5 on line " NR
}
else {
print "No kernel or systemd in Field 5 on line " NR
}
}

The Number of Records (NR) built-in variable causes the line numbers to print out along with the messages. There will be lots of output, so you might want to pipe it into less, like this:

Terminal window
donnie@fedora:~$ sudo ./awk_kernel14.awk /var/log/messages | less

Here’s a sample of the output:

Kernel here in Field 5 on line 468
Systemd here in Field 5 on line 469
Systemd here in Field 5 on line 470
No kernel or systemd in Field 5 on line 471
No kernel or systemd in Field 5 on line 472
No kernel or systemd in Field 5 on line 473
No kernel or systemd in Field 5 on line 474
No kernel or systemd in Field 5 on line 475
No kernel or systemd in Field 5 on line 476
Systemd here in Field 5 on line 477

Okay, I think you get the idea. Other than the different syntax, it’s really no different from using if in normal bash scripts. So, let’s move on for a while.

Using a while Construct and Setting Variables

Section titled “Using a while Construct and Setting Variables”

In this section, I’ll show you two new concepts at once. You’ll see how to use a while loop, and how to use awk programming variables. Let’s begin with something simple.

In this scenario, we have a file with several lines of numbers. We want to add the numbers on each line and show the sum for each line. First, create the input file and make it look something like this numbers_fields.txt file:

38 87 389 3 3432
34 13
38976 38 198378 38 3
3878538 38
38
893 18 3 384 352 3892 10921 10 384
348 35 293
93 1 2
1 2 3 4 5

This looks like quite a challenging task because each line has a different number of fields. But, it’s actually quite easy. Here’s the add_fields.awk script that does the job:

#!/usr/bin/awk -f
{
addend=1
sum=0
while (addend <= NF) {
sum = sum + $addend
addend++
}
print "Line " NR " Sum is " sum
}

The first thing I’ve done is to initialize the addend and sum variables. The addend variable represents the field numbers. By initializing it to a value of 1, the script will always begin at the first field of every line. The sum variable is initialized to 0, for obvious reasons. The while (addend <= NF) line causes the while loop to execute until it reaches the last field in a line. (The built-in NF variable holds the number of fields in a given line.) In the next line, using addendisthesameaslistingafieldnumber,suchasaddend is the same as listing a field number, such as 1 or 2.So,asyoumightexpect,2. So, as you might expect, addend returns the value that’s contained in a given field. By using a variable in place of a hard-coded field number, we can use the addend++ command in the next line to advance to the next field in a line. (This variable++ construct increments the value of the variable by 1, the same as it does in C.)

If you’re a bit confused by this, allow me to clarify.

Unlike in normal shell scripting, in awk, you don’t prefix the name of a variable with a tocallbackitsvalue.Inawk,theto call back its value. In awk, the is instead used to reference the number of a field. So, prefixing a variable name with a $ in awk just means that you’re referencing the field number that’s been assigned to that variable.

After the while loop finishes, the script prints out its message, with the sum of all the numbers on a line. Then, it returns to the beginning of the script and keeps going until all lines in the file have been processed. Here’s what the output looks like:

Terminal window
donnie@fedora:~$ ./add_fields.awk numbers_fields.txt
Line 1 Sum is 3949
Line 2 Sum is 47
Line 3 Sum is 237433
Line 4 Sum is 3878576
Line 5 Sum is 38
Line 6 Sum is 16857
Line 7 Sum is 676
Line 8 Sum is 96
Line 9 Sum is 15
donnie@fedora:~$

It works, so everything is cool. Now, let’s fancy things up a bit. Let’s add a line that will produce the average of the numbers on each line and format the output. Name the file average_fields.awk, and make it look like this:

#!/usr/bin/awk -f
{
addend=1
sum=0
while (addend <= NF) {
sum = sum + $addend
addend++
}
print "Line " NR "\n\t" "Sum: " sum "\n\t" "Average: " sum/NF
}

What’s so cool about this is that I can use the NF built-in variable in math operations. In this case, I’m just dividing the sum of each line by the number of fields in each line. The output looks like this:

Terminal window
donnie@fedora:~$ ./average_fields.awk numbers_fields.txt
Line 1
Sum: 3949
<!-- page: 407 (printed 403) -->
Average: 789.8
Line 2
Sum: 47
Average: 23.5
...
...
Line 9
Sum: 15
Average: 3
donnie@fedora:~$

If you’re used to C programming, understand that there’s a difference between how awk and C use variables. Unlike in C, it’s not necessary to declare awk variables before you use them. But, it is sometimes necessary to initialize them to a certain value before you use them. Also, unlike in C, there’s only one variable type in awk. All awk variables are of the string type, and all awk math operators automatically recognize numerical values that these variables might represent.

Next, let’s look at something a bit more complex.

Finding the CPU Generation

Let’s consider another scenario. You have an old server that’s powered by an AMD Opteron CPU. You just tried to install Red Hat Enterprise Linux 9 (RHEL 9) on it, and you can’t get it to work. What could be the problem?

Well, it’s just that your trusty Opteron CPU is too old, which means that it lacks certain capabilities that newer CPUs have. Ever since AMD created the first 64-bit x86 CPUs in 2003, both AMD and Intel have kept adding new capabilities to their newer models. In 2020, representatives from Intel, AMD, Red Hat, and SUSE got together and defined the four generations of x86_64. Each successive generation has capabilities that aren’t in the previous generations. Here’s a list of when each generation was introduced:

  • Generation 1: 2003
  • Generation 2: 2009
  • Generation 3: 2013 for Intel, 2015 for AMD
  • Generation 4: 2017 for Intel, 2022 for AMD

Software that was created for a first generation x86_64 CPU will also run fine on the three newer generations. But, if you have a newer CPU, you can make things run faster by using software that was optimized for it. Of course, that means that it won’t run on the older CPUs. So, if you’re still running a first generation x86_64 CPU, you won’t be able to run either RHEL 9 or any of its clones. (Rumor has it that RHEL 10, which should be out sometime in 2025, will require at least a third generation x86_64 CPU. You’ll find a link to the rumor in the Further Reading section.) That’s actually okay, because Red Hat’s target customers are the large enterprises that upgrade their gear on a regular basis.

This makes it very unlikely that any of them still run any of these first generation machines. This doesn’t really affect normal home users of desktop Linux, because very few home users use either RHEL or a RHEL clone for that purpose, and most non-RHEL distros still support the old machines. So, how do you know which generation your CPU is? That’s easy. Just write a script.

To get an idea of how this works, look in the /proc/cpuinfo file, and scroll down to the flags section. What you’ll see depends upon which generation of x86_64 CPU is in your machine. Here on my 2012-model Dell workstation with an Intel Xeon CPU that’s of the second generation x86_64 variety, the flags section looks like this:

flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca
cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx rdtscp lm constant_tsc
rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3
cx16 sse4_1 sse4_2 x2apic popcnt aes xsave avx hypervisor lahf_lm pti md_clear
flush_l1d

On my vintage 2009-model Hewlett-Packard machine with a pair of first generation Opteron CPUs, the flags section looks like this:

flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca
cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb
rdtscp lm 3dnowext 3dnow constant_tsc rep_good nopl nonstop_tsc cpuid extd_
apicid pni monitor cx16 popcnt lahf_lm cmp_legacy svm extapic cr8_legacy abm
sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt hw_pstate vmmcall npt lbrv
svm_lock nrrip_save

You see here that the second generation CPU in my Dell has newer capabilities, such as sse4_1, sse4_2, and a few others that aren’t in the old Opterons. On a Linux system, you can create either a bash script or an awk script that will automatically parse the /proc/cpuinfo file to determine the generation to which your CPU belongs. Here’s the x86_64_check.awk script, which I borrowed from a post on the StackExchange site:

#!/usr/bin/awk -f
BEGIN {
while (!/flags/) if (getline < "/proc/cpuinfo" != 1) exit 1
if (/cmov/ && /cx8/ && /fpu/ && /fxsr/ && /mmx/ && /syscall/ && /sse2/) level = 1
if (level == 1 && /cx16/ && /lahf/ && /popcnt/ && /sse4_1/ && /sse4_2/ && /ssse3/) level = 2
if (level == 2 && /avx/ && /avx2/ && /bmi1/ && /bmi2/ && /f16c/ && /fma/ && /abm/ && /movbe/ && /xsave/) level = 3
if (level == 3 && /avx512f/ && /avx512bw/ && /avx512cd/ && /avx512dq/ && /avx512vl/) level = 4
if (level > 0) { print "CPU supports x86-64-v" level; exit level + 1 }
exit 1
}

The first thing to note is that the whole script needs to be part of a BEGIN block. That’s because we need to process the whole cpuinfo file at once, instead of just one line at a time as awk would normally do. The BEGIN block helps us out with that.

Then, note that this script uses a different style for the if constructs. Instead of formatting them in the C language style as I showed you before, the author instead placed each if construct on its own line. Each style works equally well, and I’ll leave it to you to decide which one you like better. Anyway, here’s the breakdown of how it all works.

  • At the end of each of the first four if statements, the level variable is set to a new value.
  • The first if statement looks for capabilities that are in the first generation, and then assigns 1 as the value of level.
  • The second if statement verifies that the CPU contains level 1 capabilities, looks for another set of capabilities that are in second generation CPUs, and then assigns 2 as the value of level.
  • The process repeats for the third and fourth if statements, in order to detect either third or fourth generation CPUs.
  • Finally, the fifth if statement verifies that the value of level is greater than 0, prints out the message, and then exits the script with an exit code that’s the value of level plus 1.
  • The exit 1 line at the end causes the script to exit with exit code 1 if the script fails to run correctly for whatever reason. (The level + 1 command at the end of the fourth if statement prevents a successful run of the program from returning a 1 for the exit code. Remember, 1 is normally an exit code for a program that doesn’t run correctly.)

An interesting thing about awk variables is that all of them are string variables, which greatly simplifies the coding process. If you assign the value of 1 to the level variable, the value is stored as a string instead of as an integer. But, when you use variables to perform math operations in awk, everything works correctly because awk automatically recognizes when a string is really a number. Also, unlike bash, awk can natively perform floating point math operations. So, you can perform math operations much easier and faster in awk than you can in either bash scripting or a normal programming language. To demonstrate this, let’s run this script on my both of the workstations that I currently have running. Here’s what it looks like on my old Opteron-powered Hewlett-Packard:

Terminal window
donnie@opensuse:~> ./x86-64-level_check.awk
CPU supports x86-64-v1
donnie@opensuse:~> echo $?
2
donnie@opensuse:~>

As expected, the script shows that this is a first generation x86_64 machine. The echo $? command shows the exit code, which was created by the level + 1 command in the script. Now, here’s how it looks on my Xeon-powered Dell:

Terminal window
donnie@fedora:~> ./x86-64-level_check.awk
CPU supports x86-64-v2
donnie@fedora:~> echo $?
Terminal window
ie@fedora:~$

So yeah, everything works fine.

Ah, but wait. We’re not done yet, because I haven’t yet explained the while construct. It’s a bit tricky, so I saved it for last.

I’ve already shown you that in the /proc/cpuinfo file, the strings that you seek are in the stanza with the text string flags in the first field. But, the while (!/flags/) statement makes it appear that we’re not looking for the flags stanza. (Remember that the ! is a negation operator.) To understand what’s really going on, view the entire cpuinfo file by entering cat /proc/cpuinfo. You’ll see that the same set of information prints out once for every CPU core in your system. For example, my Dell workstation is running with an octo-core Xeon. Hyperthreading is enabled, which means that I have a total of 16 virtual CPU cores. So, running cat /proc/cpuinfo causes the same CPU information to print 16 times. You’ll also see that several more stanzas of information print out after the flags stanza. To understand how this while loop works, run the following one-line awk command:

Terminal window
donnie@fedora:~$ awk 'BEGIN {while (!/flags/) if (getline <"/proc/cpuinfo" == 1) print $0}'
processor : 0
vendor_id : GenuineIntel
...
...
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge
mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx
pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology
nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx
est tm2 ssse3 cx16 xtpd pcdm dca sse4_1 sse4_2 x2apic popcnt tsc_
deadline_timer aes xsave avx lahf_lm epb pti ssbd ibrs ibpb stibp tpr_shadow
flexpriority ept vpid xsaveopt dtherm ida arat pln pts vnmi md_clear flush_11d
donnie@fedora:~$

The flags stanza is actually just a single long line that wraps around on both your terminal and on the printed page. So, awk treats the flags line as a single record. The while (!/flags/) statement in this command causes getline to read the cpuinfo file until it encounters the first flags string. This means that the CPU information for only the first CPU core will show up, and any information that comes after the first flags line will not show up. (Yeah, it looks a bit confusing, but it makes total sense when you think about it.)

In the original script, the if (getline < “/proc/cpuinfo” != 1) exit 1 that’s within the while loop does two things for us. First, it uses the !=1 parameter to check for the existence of the cpuinfo file. If !=1, which is the same as saying not true, evaluates to true, then the script will exit with exit code 1.

If the !=1 parameter evaluates to false, which would mean that the file exists, then getline, a built-in awk function, will read in the cpuinfo file. This way, if you run this script on an operating system that doesn’t have a /proc/cpuinfo file, such as FreeBSD, it will gracefully exit.

Now, some of you might prefer using C-style syntax to make the script a bit more readable. Fortunately, that’s easy to do. Changing the style makes the script too long to show here in its entirety, but I can show you a snippet:

#!/usr/bin/awk -f
BEGIN {
while (!/flags/) {
if (getline < "/proc/cpuinfo" !=1) {
exit 1
}
}
...
...
if (level > 0) {
{ print "CPU supports x86-64-v" level; exit level + 1 }
}
exit 1
}

If you want to see the converted script in its entirety, just download the x86-64-level_check2.awk file from GitHub.

I believe that we’re done with this script. Let’s see what we can do with a for loop and an array.

Certain languages, such as Spanish and French, have the concept of masculine and feminine nouns. For this demo, we’ll work with a list of English nouns, their Spanish equivalents, and the gender designations for the Spanish nouns.

Why is someone with a French last name creating a list of Spanish words? Well, it’s just that despite my French ancestry, I chose to learn Spanish instead of French in high school. So, I do know some Spanish, but I don’t know French. (I know, I’m weird.) Also, I realize that the Spanish word camión has an accent over the last syllable. Alas, inserting accents with an English-language keyboard isn’t easily done in a plain-text file, at least not without messing up how the awk script works.

To begin, create the spanish_words.txt file, and make it look like this:

ENGLISH:SPANISH:GENDER
cat:gato:M
<!-- page: 412 (printed 1) -->
bus:camion:M
house:casa:F

As you see, we’re using colons as field separators, and using either M or F to designate if a word is masculine or feminine. The first line is a header, so we’ll need to take that into account when we process the file.

Next, create the masc-fem.awk script, like this:

#!/usr/bin/awk -f
BEGIN {FS=":"}
NR==1 {next}
$3 == "M" {masc[$2]=$1}
$3 == "F" {fem[$2]=$1}
END {
print "\nMasculine Nouns\n---";
for (m in masc)
{print m "--" masc[m]; count++}
print "\nFeminine Nouns\n---";
for (f in fem)
{print f "--" fem[f]; count2++}
print "\nThere are " count " masculine nouns and " count2 " feminine nouns."
}

In the BEGIN section, we’re setting the : as the field separator. The NR == 1 {next} line means to ignore line 1 and move on to the next line. The next two lines build the masc and fem arrays. Any line that has an M in field 3 goes into the masc array, and any line that has an F in field 3 goes into the fem array. The END section contains code that will run after the code in the main body has finished building the arrays. The two for loops work the same as you saw with the normal shell scripting for loops, except that we’re now using C language syntax. The first loop prints out the list of masculine nouns and uses the count variable to add up the total of masculine nouns. The second loop does the same for the feminine nouns, except that it uses the count2 variable to total the number of feminine nouns. Running the script looks like this:

Terminal window
donnie@fedora:~$ ./masc-fem.awk spanish_words.txt
Masculine Nouns
---
gato--cat
camion--bus
Feminine Nouns
---
<!-- page: 413 (printed 409) -->
mesa-table
casa-house
cama-bed
There are 2 masculine nouns and 3 feminine nouns.
donnie@fedora:~$

And, that’s all there is to it. Easy, right?

For our next trick, let’s do some floating-point math.

For some strange reason, you’ve found yourself working a job that requires you to keep track of weather-related statistics. Your boss has just sent you a text file that contains a list of temperatures. Some of the temperatures are Celsius temperatures, and some are Fahrenheit temperatures. Your assigned task is to convert the Fahrenheit temperatures to Celsius temperatures. You can do that the hard way by using a calculator to manually convert each Fahrenheit temperature, or you can write a script that will automate the process. You’ve decided that it would be easier to write a script. The list of temperatures is in the temps.txt file, which looks like this:

Temperature Celsius_or_Fahrenheit 32 F 212 F -40 F -14.7 F 24.6111 C 75.8 F 55.21 F 23.9444 C 29.8 F 104.34 F 98.6 F 23.1 C

The first three temperatures are checks to verify that the script works correctly. We know that 32 degrees F equals 0 degrees C, that 212 degrees F equals 100 degrees C, and finally that -40 degrees F equals -40 degrees C. If the script converts those three temperatures correctly, we can be reasonably sure that the rest of the temperatures are getting converted correctly.

Be sure that you haven’t inserted a blank line after the last temperature line, or else the script will insert non-sense information after the last actual line of output data.

There are two ways to express the conversion formula. Here’s one way:

(($1-32)*5) / 9

Here’s the other way:

($1-32)/1.8

The $1 represents the field that holds the original Fahrenheit temperature. So, we begin by subtracting 32 from the Fahrenheit value.

Either formula works equally well, so it really doesn’t matter which one we use. Just for fun, I’ll use the first method in the fahrenheit_to_celsius.awk script, which looks like this:

#!/usr/bin/awk -f
NR==1 ; NR>1{print ($2=="F" ? (($1-32)*5) / 9 : $1) "\t\t Celsius"}

As you see, it’s just a simple one-liner. The NR==1 causes the header to print out, and the NR>1 ensures that the conversions are performed only on the lines that contain actual data. The combination of the ? and the : in the print action is known as a ternary operator. If the first term ($2==“F”) evaluates to true, then the original value of field 1 will be replaced by the value that’s between the ? and the :. In this case, the new value is derived from performing the conversion calculation. After the new temperature value on each line, we want to print out a pair of tabs, followed by the word Celsius. Here’s what happens when I run the script:

Terminal window
donnie@fedora:~$ ./fahrenheit_to_celsius.awk temps.txt
Temperature Celsius_or_Fahrenheit
0 Celsius
100 Celsius
-40 Celsius
-25.9444 Celsius
24.6111 Celsius
24.3333 Celsius
12.8944 Celsius
23.9444 Celsius
-1.22222 Celsius
40.1889 Celsius
37 Celsius
23.1 Celsius
donnie@fedora:~$

That doesn’t look so good, because some of the Celsius values are longer than the others, which causes the second column of those lines to not line up correctly. We’ll fix this by using printf instead of print.

The printf command allows you to customize the output in ways that you can’t do with print. It works pretty much the same way in awk as it does in C, so once again you C programmers can rejoice. Here’s how the solution works in the fahrenheit_to_celsius2.awk script:

#!/usr/bin/awk -f
NR==1; NR>1{printf("%-11s %s\n",($2=="F" ? (($1-32)*5) / 9 : $1), "Celsius")}

The % signs in the printf command represent formatting directives. Let’s take the %-11s directive, which formats the first field in each line. The - tells printf to left-justify the output. (By default, the output is right-justified.) The 11s tells printf to allocate 11 spaces for the first field of output. If the string in any given line is less than 11 characters long, then printf will pad the output with enough blank spaces to make up the difference. Finally, %s\n causes printf to print out the designated text string as the second field, followed by a newline. (Unlike print, printf doesn’t automatically add a newline at the end of a line.) Anyway, here’s the output:

Terminal window
donnie@fedora:~$ ./fahrenheit_to_celsius2.awk temps.txt
Temperature Celsius_or_Fahrenheit
0 Celsius
100 Celsius
-40 Celsius
-25.9444 Celsius
24.6111 Celsius
24.3333 Celsius
12.8944 Celsius
23.9444 Celsius
-1.22222 Celsius
40.1889 Celsius
37 Celsius
23.1 Celsius
donnie@fedora:~$

Yes, that looks much better. But, what if you don’t need to see all of those decimal places? Easy, just use a different formatting directive for the first field, as you see here in the fahrenheit_to_celsius3. awk script:

#!/usr/bin/awk -f
NR==1; NR>1{printf("%.2f %s\n",($2=="F" ? (($1-32)*5) / 9 : $1), "Celsius")}

Here, I’m using %.2f to format the output as a floating point number with only two digits after the decimal point. Here’s how the output looks:

Terminal window
donnie@fedora:~$ ./fahrenheit_to_celsius3.awk temps.txt
Temperature Celsius_or_Fahrenheit
0.00 Celsius
100.00 Celsius
-40.00 Celsius
-25.94 Celsius
24.61 Celsius
24.33 Celsius
<!-- page: 416 (printed 12) -->
12.89 Celsius
23.94 Celsius
-1.22 Celsius
40.19 Celsius
37.00 Celsius
23.10 Celsius
donnie@fedora:~$

The only slight catch is that now the second column doesn’t line up correctly. You can’t use two directives together for a single field, so we’ll just have to live with it like this. That’s okay though, because if you decide to redirect this output into a file, you’ll still be able to import it into a spreadsheet program.

With a slight change in the formula, you can also change Celsius temperatures to Fahrenheit. Here’s the celsius_to_fahrenheit2.awk script that does that:

#!/usr/bin/awk -f
NR==1; NR>1{printf("%-11s %s\n",($2=="C" ? ($1*9) / 5 + 32 : $1),"Fahrenheit")}

And, here’s the output:

Terminal window
donnie@fedora:~$ ./celsius_to_fahrenheit2.awk temps.txt
Temperature Celsius_or_Fahrenheit
32 Fahrenheit
212 Fahrenheit
-40 Fahrenheit
-14.7 Fahrenheit
101.9 Fahrenheit
75.8 Fahrenheit
55.21 Fahrenheit
100.7 Fahrenheit
29.8 Fahrenheit
104.34 Fahrenheit
98.6 Fahrenheit
99.18 Fahrenheit
donnie@fedora:~$

Next, let’s say that we don’t care about seeing the list of temperatures, and only want to see the average. Well, here’s the average_temp.awk script which does that:

#!/usr/bin/awk -f
BEGIN{temp_sum=0; total_records=0; print "Calculate the average temperature."}
$2=="F"{temp_sum += ($1-32) / 1.8; total_records += 1;}
$2=="C" {temp_sum += $1; total_records += 1}
END {average_temp = temp_sum/total_records; print "The average temperature is:\n\t" average_temp " Celsius."}

This time, I decided to use the alternate formula for converting from Fahrenheit to Celsius. In both of the $2== lines, I’m using the += operator to sum the temperatures in the first field and to increment the total_records variable. Here’s the output:

Terminal window
donnie@fedora:~$ ./average_temp.awk temps.txt
Calculate the average temperature.
The average temperature is:
18.2421 Celsius.
donnie@fedora:~$

To verify that it’s giving you accurate averages, play around with different temperature values in the temps.txt file to see what happens.

The final thing I’ll say on this topic is that awk offers the full range of math operators, as well as a good selection of math functions. You can find out more by following the links in the Further Reading section.

Next, let’s see what we can do with multi-line records.

Working with Multi-Line Records

So far, we’ve been using awk to parse text files in which each line is its own distinct record. Sometimes though, you might have to work with files that have each record spread across several lines. For example, look at this inventory.txt file:

Kitchen spatula
$4.99
Housewares
Raincoat
$36.99
Clothing
On Sale!
Claw hammer
$7.99
Tools

The first and third records each consist of three lines, and the second record consists of four lines. Each record is separated by a blank space. Now, let’s say that we need to import this information into a spreadsheet. That won’t work well with multi-line records, so we’ll need to find an easy way to convert it into a spreadsheet-friendly format. Once again, awk to the rescue! Here’s the inventory.awk script that helps us out:

#!/usr/bin/awk -f
BEGIN {
FS="\n"
RS=""
ORS=""
<!-- page: 418 (printed 1) -->
}
{
count=1
while (count<NF) {
print $count "\t"
count++
}
print $NF "\n"
}

The BEGIN block defines the newline (\n) as the field separator, which means that each line in a record is its own field. The record separator (RS) and the output record separator (ORS) are each defined as a null value (""). The RS variable interprets the null value as a blank line, but the ORS variable doesn’t. In this case, having ORS defined as a null value just prevents the print command in the while loop from adding a newline at the end of each field.

There’s not much in the while loop that you haven’t seen before. It just uses the count variable to hold the number of the field that’s being processed. The value of this count variable gets incremented by 1 after each iteration of the while loop. You might think it strange that the loop parameter is defined as count<NF instead of count<=NF. I mean, wouldn’t we want to process the last field in every record? Well, we do process that last field with the print $NF “\n” command that comes after the while loop. As I said, defining the ORS as "" prevents the print command from adding a newline character at the end of each field. So, in order to have each record on a separate line, we have to have a separate print command for the final field, and specify that it will add a newline at the end of the line. At any rate, here’s how things look when I use the script to parse the inventory.txt file:

Terminal window
donnie@fedora:~$ ./inventory.awk inventory.txt
Kitchen spatula $4.99 Housewares
Raincoat $36.99 Clothing On Sale!
Claw hammer $7.99 Tools
donnie@fedora:~$

Of course, you can redirect the output into a .tsv file that you can open in your favorite spreadsheet program. If you’d rather use a .csv file, just replace the print count"\t"lineinthewhileloopwithprintcount "\t" line in the while loop with print count ”,”. The output will then look like this:

Terminal window
donnie@fedora:~$ ./inventory.awk inventory.txt
Kitchen spatula,$4.99,Housewares
Raincoat,$36.99,Clothing,On Sale!
Claw hammer,$7.99,Tools
donnie@fedora:~$

The beauty of this script is that it doesn’t matter how many fields you have in each record. The NF built-in variable keeps track of how many fields there are, and the while loop processes each record accordingly.

Okay, I think that this will pretty much wrap up our introduction to awk scripting. So, let’s summarize and move on.

The awk scripting language is exceedingly useful for anyone who needs to extract meaningful data from plain-text files. I began this chapter by showing you the basic construction of an awk script. Then, I showed you how to use if and if . else to create conditional commands, how to use while loops, and how to parse text files with multi-line records. For the demos, I showed you various awk scripts that do the types of jobs that you might encounter in real life.

Unfortunately, there’s no way that I can do complete justice with this presentation of awk. It’s another of those topics about which entire books have been written, so the best I can do here is to just what your appetite.

In the next chapter, we’ll get back to the main topic of shell scripting, by looking at a couple of utilities that allow you to create user interfaces for your scripts. I’ll see you there.

  1. For the best portability, which of the following shebang lines should you place in your awk scripts?

    a. #!/bin/awk

    b. #!/usr/bin/awk -f

    c. #!/bin/awk -f

    d. #!/usr/bin/awk

  2. Which of the following statements is true?

    a. All awk programming variables must be declared before you use them.

    b. There are various types of awk variables, such as integer, floating-point, and string.

    c. All awk programming variables are string-type variables.

    d. You must convert string-type variables to either integer or floating-point variables before using them in math operations.

  3. Within an awk script, how would you define the comma as the field separator?

    a. -F=,

    b. -F=”,”

    c. FS=,

    d. .FS=”,”

  1. You have a text file with several lines of numbers, with blank spaces between the numbers. Each line has a different number of numbers. You want to sum the numbers on each line. When you write an awk script to create these sums, how would you account for the fact that each line has a different number of fields?

    a. Create a variable array to hold the number of fields in each line, and use a for loop to build the array. b. Use the NF built-in variable. c. Use the NR built-in variable. d. You can only do this when each line has the same number of fields.

  2. Which of the following printf directives would you use to ensure that a floating-point number always displays with four digits after the decimal point?

    a. %.4f b. %4 c. #4.f d. #4

Further Reading

Answers

  1. b
  2. c
  3. d
  4. b
  5. a