Using awk – Part 1
local graph
Chapter 14 — Using awk – Part 1
Section titled “Chapter 14 — Using awk – Part 1”In this chapter, I’ll show you a bit about awk. It’s a programming environment with a long and storied history that dates back to the 1970s, when it was invented by Alfred Aho, Peter Weinberger, and Brian Kernighan for use with the early Unix operating systems.
There are several ways in which you can use awk. It is a full-blown programming language, so you can use it to write very complex, stand-alone programs. You can also create simple awk commands that you can either run from the command-line or from within normal shell scripts. There’s a lot to awk, and entire books have been written about it. The goal for this chapter is to show you how to use awk in normal shell scripts.
Topics in this chapter include:
- Introducing awk
- Understanding patterns and actions
- Obtaining input from text files
- Obtaining input from commands
If you’re ready to squawk with awk, let’s get started.
Introducing awk
awk is a pattern-scanning and text-processing utility that you can use to automate the process of creating reports and databases. With its built-in math functions, you can also use it to perform spreadsheet operations on text files of columnar, numerical data. The term awk comes from the names of its creators, Aho, Weinberger and Kernighan. The original version is now referred to as “old awk”. Newer implementations, such as nawk and gawk, have more features and are somewhat easier to use.
The version of awk you have depends upon which operating system you’re running. Most Linux operating systems run gawk, which is the GNU implementation of awk. There’s most always an awk symbolic link that points to the gawk executable, as you see here on my Fedora workstation:
[donnie@fedora ~]$ awk --version<!-- page: 374 (printed 1) -->GNU Awk 5.1.1, API: 3.1 (GNU MPFR 4.1.1-p1, GNU MP 6.2.1)Copyright (C) 1989, 1991-2021 Free Software Foundation.This program is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 3 of the License, or(at your option) any later version....[donnie@fedora ~]$ ls -l /bin/awklrwxrwxrwx. 1 root root 4 Jan 18 2023 /bin/awk -> gawk[donnie@fedora ~]$A notable exception is with Alpine Linux, which by default uses the lightweight awk implementation that’s built into the busybox executable. However, both gawk and mawk, another awk implementation, are available for installation from the Alpine repositories. (I couldn’t find a definitive answer for why mawk is called mawk. But, its author is Michael Brennan, so I’m guessing that it’s supposed to stand for “Michael’s awk”.)
Unix and Unix-like operating systems, such as macOS, OpenIndiana, and the various BSD distros, use nawk, which is short for “new awk”. You’ll sometimes see this referred to as the “one true awk”, partly because Brian Kernighan, one of the authors of the original awk, is one of its maintainers. However, gawk is available for installation for both FreeBSD and OpenIndiana, and mawk is available for FreeBSD.
So, what are the differences between these different awk implementations? Well, here’s a quick rundown:
-
busybox: The awk implementation that’s built into busybox is super lightweight, and is ideal for low-resource embedded systems. This is why it’s the default choice for Alpine Linux, which is also popular for embedded systems. Be aware though that it might not always have the features that you need for complex awk commands or scripts.
-
nawk: As I’ve already mentioned, nawk is the default choice for most Unix and Unix-like systems such as FreeBSD, OpenIndiana, and macOS. But, the executable file you’ll find on these systems is normally just awk, instead of nawk.
-
mawk: This is supposed to be a faster version of awk, which was created by Mike Brennan.
-
gawk: This implementation has features that the other implementations don’t have. One major enhancement is the inclusion of internationalization and localization capabilities, which facilitates creating software for different languages and locales. It also includes TCP/IP networking capabilities and enhanced features for dealing with regular expressions.
Unless I state otherwise, I’ll be showing you coding techniques that work the same on both nawk and gawk. So, let’s get started.
Understanding Patterns and Actions
An awk pattern is simply the text or the regular expression upon which an action will operate. The source can be either a plain text file or the output of another program. To begin, let’s dump the entire contents of the /etc/passwd file to the screen, like so:
[donnie@fedora ~]$ awk '{print $0}' /etc/passwdroot:x:0:0:root:/root:/bin/bashbin:x:1:1:bin:/bin:/sbin/nologin......donnie:x:1000:1000:Donald A. Tevault:/home/donnie:/bin/bashsystemd-coredump:x:986:986:systemd Core Dumper::/usr/sbin/nologinsystemd-timesync:x:985:985:systemd Time Synchronization::/usr/sbin/nologinclamupdate:x:984:983:Clamav database update user:/var/lib/clamav:/sbin/nologinsetroubleshoot:x:983:979:SELinux troubleshoot server:/var/lib/setroubleshoot:/usr/sbin/nologin[donnie@fedora ~]$In this command, the {print 0} part is the action, which must be surrounded by a pair of single quotes. The designates which field to print. In this case, the $0 causes every field to print. Specifying a pattern would cause only the lines with that pattern to print. By not specifying a pattern this time, I caused every line to print. Now, let’s say that I only want to show the line that contains a specific username. I’ll just add the pattern, like this:
[donnie@fedora ~]$ awk '/donnie/ {print $0}' /etc/passwddonnie:x:1000:1000:Donald A. Tevault:/home/donnie:/bin/bash[donnie@fedora ~]$The pattern needs to be enclosed within a pair of forward slashes, which in turn need to be within the pair of single quotes that also surround the action.
awk operates on groups of information known as records. By default, each line in a text file is one record. For now, that’s all we’re going to deal with. However, you can also have files with multi-line records, which require special techniques to process. I’ll show you that in the next chapter.
Since {print $0} is the default action, I could just omit that part and get the same result, like so:
[donnie@fedora ~]$ awk '/donnie/' /etc/passwddonnie:x:1000:1000:Donald A. Tevault:/home/donnie:/bin/bash[donnie@fedora ~]$Let’s just print out the first field of this line. Do it like this:
[donnie@fedora ~]$ awk '/donnie/ {print $1}' /etc/passwddonnie:x:1000:1000:Donald[donnie@fedora ~]$The $1 designates that I want to print field number 1. But wait though, this still isn’t right, because the command has actually printed fields 1 through 5. That’s because the default field delimiter for awk is a blank space. Field 5, which contains my full name, has a blank space between the “Donald” and the “A.” So, as far as awk is concerned, this is the beginning of the second field. To fix that, I’ll use the -F: option to make awk recognize the colon as the field delimiter, like this:
[donnie@fedora ~]$ awk -F: '/donnie/ {print $1}' /etc/passwddonnie[donnie@fedora ~]$Finally, I have the output that I want.
If you need to display more than one field, use a comma-separated list of field identifiers in the action, like this:
[donnie@fedora ~]$ awk -F: '/donnie/ {print $1, $7}' /etc/passwddonnie /bin/bash[donnie@fedora ~]$So here, I’m displaying fields 1 and 7. (Note that the comma between the field numbers is what places a blank space between the fields in the output. Omitting the comma would cause the output to not have that blank space.)
You can also pipe the output of another program into awk, like this:
[donnie@fedora ~]$ cat /etc/passwd | awk -F: '/donnie/ {print $1}'donnie[donnie@fedora ~]$Yeah, I know. It’s usually bad form to pipe cat output into another utility, when you could just directly use the other utility. But for now, this serves to demonstrate the concept.
All of the demos that I’ve shown you thus far could also have been done with cat, grep, cut, or combinations thereof. So, you could be forgiven for wondering what the point is in using awk. Well, hang on, because you’ll soon see that awk can do some awesome things that the other utilities can’t do, or can’t do as well. We’ll begin by taking a closer look at how awk can process input from plain text files.
Obtaining Input from Text Files
As you might have already guessed, the default manner in which awk operates is to read a file line-by-line, searching for the specified pattern in each line. When it finds a line that contains the specified pattern, it will perform the specified action on that line. Let’s begin by building upon the passwd file example that I showed you in the previous section.
Looking for Human Users
The /etc/passwd file contains a list of all users on the system. What I’ve always found curious is that system user accounts and normal human user accounts are all mixed together in the same file. But, let’s say that as part of your administrator duties, you need to maintain a list of normal human users on each machine. One way to do that is to use awk to search through the passwd file for the User ID Numbers (UIDs) that correspond to human users. To find out what the UID numbers for normal users are, you can look in the /etc/login.defs file that’s on most Linux systems. This file can be somewhat different on different Linux systems, so I’ll just show you how it is on my Fedora machine. On lines 142 through 145, you see this:
# Min/max values for automatic uid selection in useradd(8)#UID_MIN 1000UID_MAX 60000So, to view all human user accounts on my system, I would search for all passwd file lines where field 3 (the UID field) contains a value that is greater than or equal to 1000 and less than or equal to 60000, like so:
donnie@fedora:~$ awk -F: '$3 >= 1000 && $3 <= 60000 {print $1, $7}' /etc/passwddonnie /bin/bashvicky /bin/bashfrank /bin/bashgoldie /bin/bashcleopatra /bin/bashdonnie@fedora:~$You can also redirect the output into a text file, by placing the output redirector within the action construct, like this:
donnie@fedora:~$ awk -F: '$3 >= 1000 && $3 <= 60000 {print $1, $7 > "users.txt"}' /etc/passwddonnie@fedora:~$ cat users.txtdonnie /bin/bashvicky /bin/bashfrank /bin/bashgoldie /bin/bashcleopatra /bin/bashdonnie@fedora:~$In both examples, note how I’m using && as the and operator in the pattern portion of the command.
Tip If you plan to use this command for your own use, be sure to verify what range of UID numbers that your operating system is using. Most Linux distros use the range of 1000 through 60000, as defined in the /etc/login.defs file. Non-Linux operating systems, such as OpenIndiana and FreeBSD, don’t use a login.defs file, and I’ve not been able to find any definitive answer about what UID ranges they use. The best I can tell you about them is to look in the /etc/passwd file to see what UID is assigned to the first human user account, and to consult your organization’s policy manual to see the exact range of UID numbers that your organization wants to use for human users.
Of course, there’s no need to type this whole long command every time you want to use it. Instead, just put it into a normal shell script, which I’ll call user_list.sh. It will look something like this:
#!/bin/bashawk -F: '$3 >= 1000 && $3 <= 60000 {print $1, $7 > "users.txt"}' /etc/passwdThat’s good, but what if you need a comma-separated value (.csv) file that you can easily import into a spreadsheet? Well, I’ve got you covered. Just add a BEGIN section, where you would define the new field delimiter for the output, as well as the field delimiter for the input, like this:
donnie@fedora:~$ awk 'BEGIN {OFS = ","; FS = ":"}; $3 >= 1000 && $3 <= 60000{print $1,$7 > "users.csv"} /etc/passwddonnie@fedora:~$ cat users.csvdonnie,/bin/bashvicky,/bin/bashfrank,/bin/bashgoldie,/bin/bashcleopatra,/bin/bashvictor,/bin/bashvalerie,/bin/bashvictoria,/bin/bashdonnie@fedora:~$This might seem a bit strange, because when you define an input field delimiter in the awk action, you used the -F option. But, when you define an input field delimiter in the BEGIN section, you use the FS option. Likewise, you use OFS in the BEGIN section to define the output field delimiter. (In awk-speak, field delimiters are actually called Field Separators, which explains why these BEGIN options are called FS and OFS.)
The BEGIN section of an awk command or script is where you add any type of initialization code that you want to run before awk starts processing the input file. You can use it to define field separators, add a header to the output, or initialize global variables that you’ll use later.
That’s good, but I’d also like to see the users’ UIDs. So, I’ll just add field 3 to the mix, like this:
donnie@fedora:~$ awk 'BEGIN {OFS = ","; FS = ":"}; $3 >= 1000 && $3 <= 60000{print $1,$3,$7 > "users.csv"}' /etc/passwddonnie@fedora:~$ cat users.csvdonnie,1000,/bin/bashvicky,1001,/bin/bashfrank,1003,/bin/bashgoldie,1004,/bin/bashcleopatra,1005,/bin/bashvictor,1006,/bin/bashvalerie,1007,/bin/bashvictoria,1008,/bin/bashdonnie@fedora:~$Now that I have my awk command the way I want it, I’ll place it into the user_list2.sh shell script that will look like this:
#!/bin/bashawk 'BEGIN {OFS = ","; FS = ":"}; $3 >= 1000 && $3 <= 60000 {print $1,$3,$7 >"users.csv"}' /etc/passwdYou could write a program that does this same thing in some other programming language, such as Python, C, or Java. But, the program code would be quite complex and more difficult to get right. With awk, all it takes is just a simple single-line command.
Next, let’s see how awk can help a busy webserver administrator.
Parsing Webserver Access Logs
Section titled “Parsing Webserver Access Logs”Webserver access logs contain a lot of information that can help a website owner, a webserver administrator, or a network security administrator. There are a lot of fancy log-parsing tools that can build fancy reports that tell you everything that’s going on, if that’s what you need. But, there may be times when you’ll want to quickly extract some specific data without taking the time to run some fancy tool. There are a few different ways to do that, and awk is one of the best.
To begin the scenario, you’ll need a virtual machine with an active webserver installed. To keep things simple, I’ll just install the Apache server and the PHP module on my Fedora Server virtual machine, like this:
donnie@fedora:~$ sudo dnf install httpd phpNext, enable and start the Apache service, like this:
donnie@fedora:~$ sudo systemctl enable --now httpdTo access the server from different machines, you’ll need to open Port 80 on the firewall, like this:
donnie@fedora:~$ sudo firewall-cmd --add-service=http --permanentdonnie@fedora:~$ sudo firewall-cmd --reloaddonnie@fedora:~$Finally, in the /var/www/html/ directory, create the test.php file, with the following contents:
<?php echo "<strong><center>This is the awk Test Page</strong></center>"; ?>Reminder: To make this work, be sure to set your virtual machine up with Bridged Mode networking, so that other machines on your network can reach it. Also, be sure that the virtual machines that you use to access the webserver are also set up in Bridged Mode, so that each machine will have its own IP address in the access log file.
Now, from as many other machines as possible, access both the Fedora Webserver Test Page and the test.php page. Then, try to access a non-existent page. Your URLs should look something like this:
http://192.168.0.11http://192.168.0.11/test.phphttp://192.168.0.11/bogus.htmlOn the webserver virtual machine, open the var/log/httpd/access_log file in less, like this:
donnie@fedora:~$ sudo less /var/log/httpd/access_logNote the structure of the file, and how it uses blank spaces as field delimiters for some fields and double quotes as field delimiters for other fields. For example, here’s one entry from my own access file:
192.168.0.17 - - [18/Dec/2023:16:40:03 -0500] "GET /test.php HTTP/1.1" 200 59"-" "Mozilla/5.0 (X11; SunOS i86pc; rv:120.0) Gecko/20100101 Firefox/120.0"So, you see here that some fields are surrounded by double quotes, and others aren’t. For now, let’s look at the IP addresses that have accessed this machine, like so:
donnie@fedora:~$ sudo awk '{print $1}' /var/log/httpd/access_log | sort -V | uniq192.168.0.10192.168.0.16192.168.0.17192.168.0.18192.168.0.27192.168.0.37192.168.0.107192.168.0.251377
192.168.0.252
donnie@fedora:~$As you see, I just piped the awk output into sort -V, which I then piped into uniq. Using the -V option for sort causes the IP addresses to be sorted in correct numerical order. You can’t use the -n switch for this, because by default, sort treats the dots in the IP addresses as decimal points. The -V option overrides that behavior by doing what is called a natural sort.
This is good, except that I still don’t know how many times the webserver was accessed from each IP address. I’ll use uniq with the -c option to see that, which will look like this:
donnie@fedora:~$ sudo awk '{print $1}' /var/log/httpd/access_log | sort -V | uniq -c6 192.168.0.1020 192.168.0.1612 192.168.0.172 192.168.0.184 192.168.0.2715 192.168.0.376 192.168.0.10714 192.168.0.2516 192.168.0.252donnie@fedora:~$That’s good, but I really want to create a .csv file, as I did for my list of users. I can’t do that by defining the OFS parameter in the BEGIN section this time, because the count field isn’t created until I pipe the output into uniq -c. So, I’ll cheat a bit by installing the miller package, which is in the repositories for most Linux distros, as well as for FreeBSD. On a Mac, you should be able to install it with homebrew. Anyway, to create the .csv file, I’ll just pipe the output from this awk command into the mlr utility, which is part of the miller package. Here’s how that looks:
donnie@fedora:~$ sudo awk '{print $1}' /var/log/httpd/access_log | sort -V | uniq -c | mlr --p2c cat > ip_list.csvdonnie@fedora:~$ cat ip_list.csv6,192.168.0.1027,192.168.0.1612,192.168.0.172,192.168.0.184,192.168.0.2715,192.168.0.376,192.168.0.10714,192.168.0.2516,192.168.0.252donnie@fedora:~$The —p2c option for mlr is what converts the output to .csv format. After that is cat, which is the \1r verb. You see that this cat just dumps the output to either the screen or to a file, the same as its bash cousin does.
I’m showing you how to create .csv files, because for historical reasons, .csv is the most popular format for plain-text data files, and your employer or clients might expect you to use them. However, as we’ll see in a bit, this isn’t always the best format. In certain circumstances, you might find that your best bet is to forget about .csv files, and instead save your data to Tab Separated Value (.tsv) files, which might look something like this:
donnie@fedora:~$ cat inventory.tsvKitchen spatula $4.99 HousewaresRaincoat $36.99 Clothing On Sale!Claw hammer $7.99 Toolsdonnie@fedora:~$You can also import them into your favorite spreadsheet program, and in certain circumstances, they’re much easier to deal with.
If you need a .json file instead of a .csv file, mlr can also do that for you. You’ll just replace the —p2c option with the —ojson option, like this:
donnie@fedora:~$ sudo awk '{print $1}' /var/log/httpd/access_log | sort -V |uniq -c | mlr --ojson cat > ip_list.jsondonnie@fedora:~$ cat ip_list.json{ "1": " 6 192.168.0.10" }{ "1": " 27 192.168.0.16" }{ "1": " 12 192.168.0.17" }{ "1": " 2 192.168.0.18" }{ "1": " 4 192.168.0.27" }{ "1": " 15 192.168.0.37" }{ "1": " 6 192.168.0.107" }{ "1": " 14 192.168.0.251" }{ "1": " 6 192.168.0.252" }donnie@fedora:~$There’s a lot more that you can do with mlr than I can show you here. To learn more about it, consult either the mlr man page or the Miller Documentation web page. (You’ll find a link to the Miller page in the Further Reading section.) As good as mlr is though, it does have one flaw. That is, it can’t handle fields that contain blank spaces or commas. So, you won’t be able to use it for every field in the Apache access log.
Now, let’s say that we want to see which operating systems and browsers are accessing this server. The User Agent string that contains that information is in field 6, which is surrounded by a pair of double quotes. So, we’ll have to use the double quote as the field delimiter, like this:
donnie@fedora:~$ sudo awk -F" '{print $6}' /var/log/httpd/access_log | sort | uniqLynx/2.8.9rel.1 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/1.1.1t-freebsdLynx/2.9.0dev.10 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/3.7.1Lynx/2.9.0dev.12 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/3.7.8Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15......Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0Mozilla/5.0 (X11; SunOS i86pc; rv:120.0) Gecko/20100101 Firefox/120.0Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/113.0donnie@fedora:~$You can see here that I had to escape the double quote with a backslash, so that the shell won’t mis-interpret it.
Next, let’s look for a specific User Agent. Let’s say that we want to know how many users are using a Mac. Just add the pattern, like this:
donnie@fedora:~$ sudo awk -F" '/Mac OS X/ {print $6}' /var/log/httpd/access_log | sort | uniq -c8 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.156 Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:109.0) Gecko/20100101 Firefox/115.06 Mozilla/5.0 (Macintosh; PPC Mac OS X 10.4; FPR10; rv:45.0) Gecko/20100101 Firefox/45.0 TenFourFox/74509 Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_4_11; en) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/4.1.3 Safari/533.19.4donnie@fedora:~$The entries for the Intel Mac are from my 2010-model Mac Pro, so they make sense. But, what’s with that PPC business in lines 3 and 4 of the output? Well, that’s also easily explained. Just for fun, I fired up my 21-year old eMac that’s equipped with an old-school Motorola PowerPC G4 processor, and used it to access the test webserver. (I’m guessing that you’ll never see any of those on your own network.)
You can also obtain this information with nothing but pure awk, without having to pipe the output into other utilities. Do that by building an associative array, which looks like this:
donnie@fedora:~$ sudo awk '{count[$1]++}; END {for (ip_address in count) print ip_address, count[ip_address]}' /var/log/httpd/access_log
<!-- page: 384 (printed 380) -->
192.168.0.251 14192.168.0.252 6192.168.0.10 6192.168.0.16 27192.168.0.17 12192.168.0.107 6192.168.0.18 2192.168.0.27 4192.168.0.37 15donnie@fedora:~$Add a BEGIN section with an OFS definition, and you can create a .csv file. Here’s how that looks:
donnie@fedora:~$ sudo awk 'BEGIN {OFS = ","}; {count[$1]++}; END {for (ip_address in count) print ip_address, count[ip_address]}' /var/log/httpd/access_log > ip_addresses.csvdonnie@fedora:~$ cat ip_addresses.csv192.168.0.251,14192.168.0.252,6192.168.0.10,6192.168.0.16,27192.168.0.17,12192.168.0.107,6192.168.0.18,2192.168.0.27,4192.168.0.37,15donnie@fedora:~$Unlike the normal shell scripting arrays that you’ve seen previously, awk associative arrays use text strings, instead of numbers, as their indexes. Also, arrays in awk are defined on-the-fly, and don’t have to be declared before you can use them. So here you see the count array, with whatever the respective values of field 1 are for the index values. The ++ operator, which assumes an initial value of 0, adds together the number of times each index string is found in the file. The first portion of this command, which ends at the semi-colon, processes the file line-by-line as awk normally does. The END keyword designates code that will run after the line-by-line processing has completed. In this case, you see a for loop that prints out a summary of unique IP addresses, along with how many times each one was found. Unfortunately, there’s no easy way to sort the output with pure awk, but you can still pipe the output into sort, like this:
donnie@fedora:~$ sudo awk 'BEGIN {OFS = ","}; {count[$1]++}; END {for (ip_address in count) print ip_address, count[i]}' /var/log/httpd/access_log | sort-t, -V -k1,1 > ip_addresses.csvdonnie@fedora:~$ cat ip_addresses.csv192.168.0.10,6192.168.0.16,27192.168.0.17,12192.168.0.18,2192.168.0.27,4192.168.0.37,15192.168.0.107,6192.168.0.251,14192.168.0.252,6donnie@fedora:~$To make this work, I’m using sort with the -t, option to define the comma as the field delimiter. (Yeah, I know. It would be nice if all Linux and Unix utilities used the same option switch to define field delimiters, but that’s just not how the world works.)
Another difference with using pure awk is that the number of occurrences for each IP address is in the second column, rather than in the first column as you saw before. That’s okay here, but it might not work so well for other fields. For example, let’s change the command to look at the User Agents in field 6:
donnie@fedora:~$ sudo awk -F" '{count[$6]++}; END { for (i in count) print i, count[i]}' /var/log/httpd/access_log | sortLynx/2.8.9rel.1 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/1.1.1t-freebsd 2Lynx/2.9.0dev.10 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/3.7.1 4Lynx/2.9.0dev.12 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/3.7.8 3Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15 8......Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/113.06donnie@fedora:~$Yeah, it works, but having the number of occurrences in the second column for this makes the output somewhat less readable.
As I mentioned before, the .csv format isn’t always your best choice for a plain-text data file. In fact, it’s impossible to turn the output from field 6 into a proper .csv file that any spreadsheet program will properly display. That’s because this field contains blank spaces and commas that make a spreadsheet program think that there are more fields in the .csv file than there really are.
So, the easiest solution is to surround the text in field 6 with a pair of double quotes and save the output to a .tsv file. Then, when you open the file in your spreadsheet, define the ” as the field delimiter. Anyway, here’s the command to create the .tsv file, without using an associative array:
donnie@fedora:~$ sudo awk 'BEGIN {FS="\""} {print "\"" $6 "\"" }' /var/log/httpd/access_log | sort | uniq -c | sort -k 1,1 -nr > user_agent.tsvdonnie@fedora:~$By default, awk strips out the double quotes that surround field 6 in the original log file. So, to make this work properly, I have to put them back into the final output file. In the action part, you see that I’m printing a double quote both before and after $6. By omitting the commas that you might normally place between the various print elements, I’ll ensure that there are no blank spaces between the quotes and the text. Then, I’m just piping the output into sort, uniq, and sort again as I’ve shown you before. Here’s how the file looks:
donnie@fedora:~$ cat user_agent.tsv23 "Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101Firefox/120.0"9 "Mozilla/5.0 (X11; SunOS i86pc; rv:120.0) Gecko/20100101 Firefox/120.0"9 "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_4_11; en)AppleWebKit/533.19.4 (KHTML, like Gecko) Version/4.1.3 Safari/533.19.4"8 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15(KHTML, like Gecko) Version/14.1.2 Safari/605.1.15"6 "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101Firefox/113.0"......3 "Lynx/2.9.0dev.12 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/3.7.8"2 "Lynx/2.8.9rel.1 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/1.1.1t-freebsd"donnie@fedora:~$If you prefer to use an associative array, you can do it like this:
donnie@fedora:~$ sudo awk -F' ' '{count[$6]++}; END { for (ip_address in count)printf "%s \"%s\"\n", count[ip_address], ip_address}' /var/log/httpd/access_log| sort -nr > user_agent.tsvdonnie@fedora:~$ cat user_agent.tsv23 "Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101Firefox/120.0"9 "Mozilla/5.0 (X11; SunOS i86pc; rv:120.0) Gecko/20100101 Firefox/120.0"9 "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_4_11; en)AppleWebKit/533.19.4 (KHTML, like Gecko) Version/4.1.3 Safari/533.19.4"8 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15(KHTML, like Gecko) Version/14.1.2 Safari/605.1.15"6 "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101Firefox/113.0"......3 "Lynx/2.9.0dev.12 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/3.7.8"<!-- page: 387 (printed 383) -->2 "Lynx/2.8.9rel.1 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/1.1.1t-freebsd"donnie@fedora:~$Note how I had to surround the printf parameters with a pair of double quotes. The first %s parameter is for the count field, and the second %s parameter is for the user agent field. To add the double quotes in the proper places, I added a ” to both before and after the second %s. Using either the associative array method or the non-associative array method gives me the same results. Now, when I open the file in a spreadsheet program, I’ll just define the double quote as the field delimiter. Here’s how that looks on LibreOffice Calc:
I know that I haven’t fully explained print versus printf yet, but I will in the next chapter.
The user_agent.tsv file should now display properly, with the count in the first column and the User Agent string in the second column.
Next, let’s count the number of times that each URL on the webserver was hit. I like having the count as the first field of output, so I’ll again pipe the awk output into uniq and sort, like so:
donnie@fedora:~$ sudo awk '{print $7}' /var/log/httpd/access_log | sort | uniq -c | sort -k1,1 -n1 /something.html1 /test1 /test.html1 /test/php1 /test.php?module=..../2 /test.php?module=....../....../....../....../....../....../....../....../....../....../proc/self/environ%00002 /test.php?page=....../....../....../....../....../....../....../....../....../proc/self/environ%0011 /icons/poweredby.png11 /poweredby.png11 /report.html12 /favicon.icoUsing the blank space as the field delimiter means that the URL field is field 7. At the end, I’m piping the output into sort again so that the list will print out according to the number of hits for each URL. But actually, I’d like that to show the most popular URLs at the top of the list. So, I’ll just add the -r option to sort in reverse, like this:
donnie@fedora:~$ sudo awk '{print $7}' /var/log/httpd/access_log | sort | uniq -c | sort -k1,1 -nr18 /test.php17 /12 /favicon.ico11 /report.html11 /poweredby.png11 /icons/poweredby.png2 /test.php?page=.../.../.../.../.../.../.../.../.../.../.../.../proc/self/environ%002 /test.php?module=.../.../.../.../.../.../.../.../.../.../.../.../proc/self/environ%00001 /test.php?module=..../1 /test/php1 /test.html1 /test1 /something.htmldonnie@fedora:~$One thing we see is that someone tried to perform a directory traversal attack against me, as evidenced by the lines that begin with /test.php?page or /test.php?module. I’ll show you more about that later in Chapter 18, Shell Scripting for Security Professionals.
That last field we’ll look at is field 9, which is the HTTP status code. Again, we’ll use the blank space as the field delimiter, like so:
donnie@fedora:~$ sudo awk '{print $9}' /var/log/httpd/access_log | sort | uniq -c | sort -k1,1 -nr53 20017 40417 4032 304donnie@fedora:~$Here’s the breakdown of what these codes mean:
- 200: The 200 code means that users were able to access web pages normally, with no problems.
- 304: The 304 code just means that when a user reloaded a page, nothing on the page had changed, so that it didn’t need to be reloaded.
- 403: The 403 code means that someone tried to access a page for which the user wasn’t authorized.
- 404: The 404 means that a user tried to access a page that doesn’t exist.
Okay, all this is good. So now, let’s put all this into the access_log_parse.sh script, which will look like this:
#!/bin/bash#timestamp=$(date +%F_%I-%M-%p)awk 'BEGIN {FS="\""} {print "\"" $6 "\""}' /var/log/httpd/access_log | sort |uniq -c | sort -k 1,1 -nr > user_agent_$timestamp.tsvawk '{print $1}' /var/log/httpd/access_log | sort -V | uniq -c | sort -k1,1 -nr >> source_IP_addresses_$timestamp.tsvawk '{print $7}' /var/log/httpd/access_log | sort | uniq -c | sort -k1,1 -nr > URLs_Requested_$timestamp.tsvawk '{print $9}' /var/log/httpd/access_log | sort | uniq -c | sort -k1,1 -nr > HTTP_Status_Codes_$timestamp.tsvI’ve decided that I want to create a separate .tsv file for each function, and that I want to have a timestamp in each filename. The %F option for date prints the date in YEAR-MONTH-DATE format, which is fine. I could have used the %T option to print the time, but that would have placed colons in the filenames, which would require me to escape the colons every time I want to access one of these files from the command line. So, I instead used the %I-%M-%p combination, in order to replace the colons with dashes. (To see more formatting options, consult the date man page.) The rest of the script consists of the commands that you’ve already seen, so I won’t repeat any of those explanations.
Of course, you can fancy up any of these scripts to meet your own desires and needs. Just use the techniques that I’ve shown you in previous chapters to add markup language tags to the output, and convert the output files to .html or .pdf format. For the multi-function script that I’ve just now shown you, you could add either if..then or case constructs that would allow you to choose the specific function that you want to run. And, don’t feel bad if you need to refer back to the previous chapters to see how any of this is done. Trust me, I won’t hold it against you.
So far, we’ve been parsing through the entire file to find what we want to see. Sometimes though, you might just want to view information from either a specific line or range of lines. For example, let’s say that you just want to see line 10. Do it like this:
donnie@fedora:~$ sudo awk 'NR == 10' /var/log/httpd/access_logThe NR variable represents the Number of Record. Since each record in the access_log file consists of only a single line, this is the same as defining the line number that you want to see. To see a range of lines, do something like this:
donnie@fedora:~$ sudo awk 'NR == 10, NR == 15 {print $1}' /var/log/httpd/access_log192.168.0.16192.168.0.16192.168.0.16192.168.0.107192.168.0.107192.168.0.107donnie@fedora:~$Here, I’m looking at field 1 of lines 10 through 15. Of course, you could do the same thing by combining the tail, head, and cut utilities, but this is way easier.
In this section, we’ve looked at FS, OFS, and NR. What I haven’t told you yet is that these three constructs are variables that are built into awk. There are many more built-in variables, but I’d rather not overwhelm you by explaining all of them now. If you’re interested in reading about all of them, just open the awk man page and scroll down to the Built-in Variables section.
The log parsing techniques that I’ve presented here can be used for any type of log file. To design your awk commands, look through the log files that you want to process and take note of how the fields are laid out in each line, and what information they contain.
Before we move on, let’s look at a few other log-parsing techniques.
Using Regular Expressions
You can enhance your awk experience with regular expressions, just as you can with other text-manipulation utilities.
If you need to, refer back to Chapter 2, Text Stream Filters – Part 2 and Chapter 9, Filtering Text with grep, sed, and Regular Expressions to review the concepts of regular expressions and POSIX character classes.
For our first example, let’s say that you need to search through the /etc/passwd file for all users whose usernames begin with a lower-case v. Just use a simple regular expression, which will look like this:
donnie@fedora:~$ awk '/^v/' /etc/passwdvicky:x:1001:1001::/home/vicky:/bin/bashvictor:x:1006:1006::/home/victor:/bin/bashvalerie:x:1007:1007::/home/valerie:/bin/bashvictoria:x:1008:1008::/home/victoria:/bin/bashdonnie@fedora:~$This works because the username field is the first field of every line. So, you don’t need to do anything any fancier than just this. But, let’s suppose you need to search for something in another field that begins with a certain character. For example let’s say that you need to search through the Apache access log file for all HTTP status codes that are in the 400 range. Just do something like this:
donnie@fedora:~$ sudo awk '$9 ~ /^4/{print $9}' /var/log/httpd/access_log | sort -n | uniq -c17 40320 404donnie@fedora:~$The $9 in the pattern means that you’re looking for a certain pattern in field 9. The ~ means that you want something in that field to match whatever is within the following forward slashes. In this case, it’s looking for anything in field 9 that begins with the number 4. In the output, you see that I’ve found both the 403 and the 404 status codes. And, if you need to, you can save the output to a .csv file, like so:
donnie@fedora:~$ sudo awk '$9 ~ /^4/{print $9}' /var/log/httpd/access_log | sort -n | uniq -c | mlr --p2c cat > status_code.csvdonnie@fedora:~$ cat status_code.csv17,40320,404donnie@fedora:~$If you prefer, you can save it to a .tsv file by omitting the mlr —p2c cat portion, like so:
donnie@fedora-server:~$ sudo awk '$9 ~ /^4/{print $9}' /var/log/httpd/access_log | sort -n | uniq -c > status_code.tsvdonnie@fedora-server:~$ cat status_code.tsv6 4034 404donnie@fedora-server:~$To print everything except for a certain pattern, use the !~ construct, like this:
donnie@fedora:~$ sudo awk '$9 !~ /^4/{print $9}' /var/log/httpd/access_log |sort -n | uniq -c53 2002 304donnie@fedora:~$This allows us to see everything except for the 400 codes.
Next, let’s say that we want to see all instances where someone used either the Safari or the Lynx web browsers. You could do this:
donnie@fedora:~$ sudo awk '/Safari|Lynx/' /var/log/httpd/access_logHowever, that doesn’t work, because it will include entries like this one:
192.168.0.27 - - [17/Dec/2023:17:43:40 -0500] "GET / HTTP/1.1" 403 8474 "-""Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, likeGecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0"For some strange reason, Apache can’t exactly identify the Microsoft Edge browser, so it reports it as several different possibilities, including Safari. To narrow that down, I’ll exclude any users who are using Windows. (Safari used to be available for Windows, but the Windows version was discontinued in 2012.) Here’s how that looks:
donnie@fedora:~$ sudo awk -F' ' '$6 !~ /Safari|Lynx/ && $6 !~ /Windows/' /var/log/httpd/access_logAnd here, you see something that’s rather strange. It’s that when you use an or or an and operator within a regular expression, you use either a single | or a single &. When you use an or or an and operator outside of a regular expression, you use either || or &&. I know, it’s confusing, but that’s just the way it is. Anyway, if you look through the output now, you’ll see that there are no lines from the Windows users.
I know, this is just scratching the surface for what you can do with awk and regular expressions. If you ask real nicely, I might show you a few more examples in the next section, which will be about how to use awk to process information from other commands.
Obtaining Input from Commands
Let’s start with something simple, by obtaining some basic process information. On the Fedora Server virtual machine that’s running Apache, search for all ps aux output lines that contain the httpd pattern, like so:
donnie@fedora:~$ ps aux | awk '/httpd/ {print $0}'root 1072 0.0 0.2 19108 10796 ? Ss 14:36 0:01 /usr/sbin/httpd -DFOREGROUND<!-- page: 393 (printed 389) -->apache 1111 0.0 0.1 19204 6788 ? S 14:36 0:00 /usr/sbin/httpd -DFOREGROUNDapache 1112 0.0 0.2 2158280 8448 ? S1 14:36 0:02 /usr/sbin/httpd -DFOREGROUNDapache 1113 0.0 0.2 2420488 8592 ? S1 14:36 0:03 /usr/sbin/httpd -DFOREGROUNDapache 1114 0.0 0.2 2158280 8448 ? S1 14:36 0:02 /usr/sbin/httpd -DFOREGROUNDdonnie 1908 0.0 0.0 9196 3768 pts/0 S+ 17:13 0:00 awk /httpd/{print $0}donnie@fedora:~$Next, let’s say that we want to see all processes that are owned by the root user. That’s also easy. Just do this:
donnie@fedora:~$ ps aux | awk '$1 == "root" {print $0}'root 1 0.0 0.6 74552 27044 ? Ss 14:26 0:05 /usr/lib/systemd/systemd --switched-root --system --deserialize=36 rhgbroot 2 0.0 0.0 0 0 ? S 14:26 0:00 [kthread]root 3 0.0 0.0 0 0 ? S 14:26 0:00 [pool_workqueue_release]......root 1688 0.0 0.1 16332 6400 ? S 16:53 0:00 systemd-userwork: waiting...donnie@fedora:~$There’s nothing really new here, because these awk commands are the same as you saw in the previous section. Indeed, pretty much all of the techniques that you can do with parsing log files also work here. So, let’s not repeat any more of that.
The first step for parsing information from the ps utility is to see what the various fields are. The aux combination of options is what I find most useful for myself, simply because it displays the specific information that I most need to see. To see the ps header that shows the field names, I’ll pipe the ps aux output into head -1, like this:
[donnie@fedora ~]$ ps aux | head -1USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND[donnie@fedora ~]$Here’s the breakdown of what all these fields represent:
- USER: The user that owns each particular process.
- PID: The Process ID number of each process.
- %CPU: The percentage of CPU resources that each process consumes.
- RSS: The Resident Set Size is the amount of actual physical, non-swapped memory that each process uses. (I know that this is out of order, but you’ll soon see the reason.)
- %MEM: The ratio of the process’s RSS to the amount of physical memory that’s installed in the machine.
- VSZ: The Virtual Set Size is the amount of virtual memory that each process is using. (This is expressed in numbers of 1024-byte units.)
- TTY: This is the terminal which is controlling each process.
- STAT: This column holds the status code of each process. START: The starting time or date of each process.
- TIME: This is the cumulative CPU time for each process, in “[DD-]HH:MM:SS” format. COMMAND: The commands that started each process.
Bear in mind that there are many options switches for ps, which all show different types of process data. There are also many ways to combine the switches in order to get all of the information you need, displayed in your preferred format. For now though, I’m just going to stick with ps aux, mainly because it’s the most useful option combination for me. For more details, see the ps man page.
By default, ps commands always display this header along with the information that you want to see. So, you’ll see this header if you pipe ps into an awk command that doesn’t filter it out. For example, let’s look at the processes that are not owned by the root user, like this:
donnie@fedora:~$ ps aux | awk '$1 != "root" {print $0}'USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDsystemd+ 800 0.1 0.1 16240 7328 ? Ss 14:270:13 /usr/lib/systemd/systemd-oomdsystemd+ 801 0.0 0.4 27656 16236 ? Ss 14:270:00 /usr/lib/systemd/systemd-resolved......donnie 1745 200 0.1 9888 4520 pts/0 R+ 17:100:00 ps auxdonnie 746 0.0 0.0 9196 3804 pts/0 S+ 17:100:00 awk '$1 != "root" {print $0}'donnie@fedora:~$That’s fine most of the time. But, having that header there might mess you up if you need to save the information to a formatted text file. To fix this, let’s use the Number of Record (NR) variable that I showed you in the previous section. Here’s how that works:
donnie@fedora:~$ ps aux | awk 'NR > 1 && $1 != "root" {print $0}'systemd+ 800 0.1 0.1 16240 7328 ? Ss 14:27 0:15 /usr/lib/systemd/systemd-oomdsystemd+ 801 0.0 0.4 27656 16236 ? Ss 14:27 0:00 /usr/lib/systemd/systemd-resolved...donnie 1765 250 0.1 9888 4620 pts/0 R+ 17:26 0:00 ps auxdonnie 1766 0.0 0.0 9196 3780 pts/0 S+ 17:26 0:00 awk NR > 1&& $1 != "root" {print $0}donnie@fedora:~$The NR > 1 clause means that we only want to see records that come after record 1. In other words, we don’t want to see the first line of output, which in this case would be the ps header.
Now that we know what each field is, we can create some useful one-liners to extract information. First, let’s see how many processes are in either the Running state or the Zombie state. (A Zombie process is a dead process that hasn’t yet been properly destroyed by its parent process. You can view the ps man page to learn more about them.) We know that the STAT column is field 8, so the command will look like this:
[donnie@fedora ~]$ ps aux | awk '$8 ~ /^[RZ]/ {print}'donnie 2803 30.5 1.6 4963152 1058324 ? R1 14:00 70:12 /usr/lib64/firefox/firefoxdonnie 4383 1.9 0.4 3157216 307460 ? R1 14:03 4:18 /usr/lib64/firefox/firefox -contentproc -childID 33 -isForBrowser -prefsLen 31190-prefMapSize 237466 -jsInitLen 229864 -parentBuildID 20231219113315 -greomni /usr/lib64/firefox/omni.ja -appomni /usr/lib64/firefox/browser/omni.ja -appDir /usr/lib64/firefox/browser {d458c911-d065-4a3c-bdd5-9d06fc1d030d} 2803 true tabdonnie 46283 0.0 0.0 0 0 ? R 17:50 0:00 [ChrootHelper]donnie 46315 0.0 0.0 224672 3072 pts/0 R+ 17:50 0:00 ps aux[donnie@fedora ~]$It looks a bit jumbled up because the COMMAND field for the second process contains a very long string, but that’s okay. You can still see that field 8 in every line begins with the letter R. (You’ll rarely see any Zombie processes on your systems, so don’t worry about not seeing any of them here. And no, Zombie processes don’t go around looking for brains to steal.)
The w command shows you a list of all users who are logged into the system, and what they’re doing. It looks like this:
donnie@fedora:~$ w17:37:44 up 3:11, 4 users, load average: 0.03, 0.06, 0.02USER TTY LOGIN@ IDLE JCPU PCPU WHATdonnie tty1 17:31 5:51 0.06s 0.06s -bashdonnie pts/0 15:29 0.00s 0.35s 0.06s wvicky pts/1 17:32 4:50 0.05s 0.05s -bashYou see that I’m logged in via tty1, which is the local terminal. I’m also logged in remotely via a pts terminal, along with Vicky and Frank. (Remember that tty terminals indicate that someone is logged in locally, while pts terminals indicate that someone is logged in remotely.) Now, let’s use ps to see more information about the processes that the remote users are running, like this:
donnie@fedora:~$ ps aux | awk '$7 ~ "pts"'donnie 1492 0.0 0.1 8480 5204 pts/0 Ss 15:29 0:00 -bashvicky 1845 0.0 0.1 8348 4960 pts/1 Ss+ 17:32 0:00 -bashfrank 1892 0.0 0.1 8348 5000 pts/2 Ss+ 17:33 0:00 -bashdonnie 1936 200 0.1 9888 4640 pts/0 R+ 17:37 0:00 ps auxdonnie 1937 0.0 0.0 9064 3908 pts/0 S+ 17:37 0:00 awk '$7 ~ "pts"'donnie@fedora:~$A few moments ago, I showed you how to strip the header line out of the output if your awk command doesn’t already strip it out. This time, the awk command does strip it out, but I’ve decided that I want to see it. To fix that, I’ll do this:
donnie@fedora:~$ ps aux | awk '$7 ~ "pts" || $1 == "USER"'USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDdonnie 1492 0.0 0.1 8480 5204 pts/0 Ss 15:29 0:00 -bashvicky 1845 0.0 0.1 8348 4960 pts/1 Ss+ 17:32 0:00 -bashfrank 1892 0.0 0.1 8348 5000 pts/2 Ss+ 17:33 0:00 -bashdonnie 2029 400 0.1 9888 4416 pts/0 R+ 17:48 0:00 ps auxdonnie 2030 0.0 0.0 9064 3928 pts/0 S+ 17:48 0:00 awk '$7 ~ "pts" || $1 == "USER"'donnie@fedora:~$Note here that I’m using two different methods of finding a pattern. The $7 ~ "pts" portion finds all lines that contain the pts text string in field 7. So, we see that pts/0, pts/1, and pts/2 all match this search criterion. The $1 == "USER" portion is looking for an exact, whole-word match. To demonstrate, look at this user.txt file:
[donnie@fedora ~]$ cat user.txtUSER donnieUSER1 vickyUSER2 cleopatraUSER3 sylvester[donnie@fedora ~]Using the ~ to search for all lines with USER in field 1 gives us this:
[donnie@fedora ~]$ awk '$1 ~ "USER" {print $1}' user.txtUSERReplacing the ~ with == gives us this:
[donnie@fedora ~]$ awk '$1 == "USER" {print $1}' user.txtUSER[donnie@fedora ~]$So you see that there is a big difference. Also, note that since I’m searching for a literal text string, I can surround the search term (USER) within either a pair of double quotes or a pair of forward slashes when using the ~. However, when using the ==, you’ll need to use the double quotes, because using the double slashes shows you nothing.
And, with that bit of a digression out of the way, let’s get back to our regularly scheduled program.
I’ve now decided that I want to see all processes with a virtual memory size (VSZ) of more than 500,000 bytes. VSZ information is in field 5, so my awk command looks like this:
donnie@fedora:~$ ps aux | awk '$5 > 500000 {print $0}'USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDapache 1098 0.0 0.2 2420488 8628 ? S1 14:28 0:04 /usr/sbin/httpd-DFOREGROUNDapache 1099 0.0 0.2 2223816 8248 ? S1 14:28 0:03 /usr/sbin/httpd-DFOREGROUNDapache 1100 0.0 0.2 2158280 8232 ? S1 14:28 0:04 /usr/sbin/httpd-DFOREGROUNDdonnie@fedora:~$But, that’s more information than I really need. I just want to look at the relevant fields, and I’ve decided to place each field on its own line, along with a label. Here’s how I’ll do it:
donnie@fedora:~$ ps aux | awk 'NR > 1 && $5 > 500000 {print "USER: " "\t\t" $1 "\n" "PID: " "\t\t" $2 "\n" "VSZ: " "\t\t" $5 "\n" "COMMAND: " "\t" $11 "\n\n"}'USER: apachePID: 1147VSZ: 2354952COMMAND: /usr/sbin/httpdUSER: apachePID: 1148VSZ: 2158280COMMAND: /usr/sbin/httpdUSER: apachePID: 1149<!-- page: 398 (printed 394) -->VSZ: 2158280COMMAND: /usr/sbin/httpddonnie@fedora:~$As noted before, NR > 1 prevents ps from printing the default header. In the action, the print command places a pair of tabs (\t\t) between USER, PID, VSZ, and their respective values. The COMMAND label is longer, so it only requires one tab (\t) between it and its values. This ensures that all values in the second column line up nice and neat. The newlines (\n) after the USER, PID, and VSZ values cause the next field to print on a new line. After the COMMAND value, I placed two newlines (\n\n) so that there would be a blank line between each record.
Next, let’s turn this command into a function that we can add to the sysinfo.lib function library that showed you in Chapter 10—Understanding Functions. Our new VSZ_info() function looks like this:
VSZ_info() { echo "<h2>Processes with more than 500000 bytes VSZsize.</h2>" echo "<pre>" ps aux | awk 'NR > 1 && $5 > 500000 {print "USER:" "\t\t" $1 "\n""PID:" "\t\t" $2 "\n" "VSZ:" "\t\t" $5 "\n" "COMMAND:" "\t" $11 "\n\n"}' echo "</pre>"}Now, in the system_info.sh script that I also showed you in Chapter 10, you’ll need to add $(VSZ_info) to the end of the list of functions that the script calls. Now when you run the script, you’ll see the VSZ information at the end of the output file. (Both files are too long to reproduce here, but you can download them from GitHub.)
Okay, that about wraps it up for the basics of using awk in shell scripts. Let’s summarize and move on.
Summary
In this chapter, I introduced you to the sacred mysteries of using awk. We started by looking at the numerous implementations of awk, and at how a basic awk command is constructed. Next, we saw how to use awk to process information either from a text file or from another program. Then, we saw how to run awk commands from within a normal shell script. Finally, we turned an awk command into a function, and added it to our function library file.
In the next chapter, we’ll look at how to create awk program scripts. I’ll see you there.
Questions
-
What are the two parts of an awk command? (Choose two.)
a. action b. expression c. pattern d. command e. order
-
What does {print 0} do in an awk command? a. It prints the name of the script that you're running, because 0 is the bash positional parameter that hold the name of the script. b. It prints the value that was assigned to the 0 variable. c. It prints all fields of a record. d. It’s an invalid command that doesn’t do anything.
-
You want to perform an exact, whole-word match for all lines that contain a certain text string. Which of the following awk operators would you use? a. == b. = c. eq d. ~
-
Where is the best place to define values for FS and OFS? a. In the END section of an awk command. b. You can’t. They already have pre-defined values. c. In the BEGIN section of an awk command. d. In the action of an awk command.
-
How do you use regular expressions with awk? a. Surround the regular expression with a pair of forward slashes. b. Surround the regular expression with a pair of single quotes. c. Surround the regular expression with a pair of double quotes. d. Don’t surround the regular expression with anything.
Further Reading
- The GNU awk Users’ Guide: https://www.gnu.org/software/gawk/manual/gawk.html
- Awk by Example: https://developer.ibm.com/tutorials/1-awk1/
- awklang.org—The site for things related to the awk language: http://www.awklang.org/
- awk: One True awk: https://github.com/onetrueawk/awk
- Awk Scripts YouTube channel: https://www.youtube.com/@awkscripts
- Miller Documentation: https://miller.readthedocs.io/en/latest/
- The GAWK Manual-Useful “One-liners”: http://web.mit.edu/gnu/doc/html/gawk_7.html
- How to Use awk in Bash Scripting: https://www.cyberciti.biz/faq/bash-scripting-using-awk/
- Advanced Bash Shell Scripting Guide-Shell Wrappers: https://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/wrapper.html
- Awk: The Power and Promise of a 40-year-old Language: https://www.fosslife.org/awk-power-and-promise-40-year-old-language
Answers
- a and c
- c
- a
- c
- a
Join our community on Discord! Read this book alongside other users, Linux experts, and the author himself.
Ask questions, provide solutions to other readers, chat with the author via Ask Me Anything sessions, and much more. Scan the QR code or visit the link to join the community.