This Is awk-ward: How To Get The Last String On A Line

This Is awk-ward:  How To Get The Last String On A Line

Did you say ‘hawk’?

No.  It’s awk.  That’s the name of a scripting language that is available on most Linux based systems.  The language takes its odd name from the first initials of the developers who created it:  Aho, Weinberger, and Kernighan.

Another scripting language?

You’re probably wondering why there are so many scripting languages in Linux.  Think of a mechanic’s toolbox.  There are probably two or more tools in there that you can use to unscrew a bolt but there’s always one tool that’s best for a particular situation.  Same thing with scripting languages.  awk is a scripting language can be used for quickly scanning text files for a particular pattern.

Give me an example

Let’s say you have a line in a text file made of multiple strings like this:

string1 string2 string3

Now let’s say you only want to get the last string on the line.  If you were using grep the command would look something like this:

% grep -oE '[^ ]+$' scan_this_file.txt
string3

Notice the items in single quotes.  If you’re not familiar with regex patterns, you would have to decipher what the characters in the single quotes meant.  Let’s compare that command to the equivalent in awk:

% awk '{print $NF}' scan_this_file.txt
string3

Notice how much cleaner the second command is.  The $NF variable stands for number of fields which, in this case, is 3.  So using the $NF field is equivalent to typing $3.  Oh sure, you say, that was easy because you’re looking for the last string on the line.  What if you wanted the string in the middle?  In this case, we could use this command:

% awk '{print $2}' scan_this_file.txt
string2

Notice that awk provides variables that can make extracting fields much easier.  If I wanted to only extract the first and last strings I could use this command:

% awk '{print $1, $NF}' scan_this_file.txt
string1 string3

So does that mean you will never have to use regex patterns in awk?  No.  If you are working with any type of parsing in Linux you will have to learn how to use regex at some point.  And that’s not a bad thing since regular expressions are very powerful but we’ll leave those for another time.

Conclusion

When you are parsing text files, you have lots of tools at your disposal but some are better than others depending on the information you want to get.  If every need to quickly extract specific fields from a line in a text file, awk can help you do that without having to come up without having to use a regex pattern.  Happy scripting.