Tuesday, March 17, 2009

Awk

Table of Contents

Copyright 2001,2004 Bruce Barnett and General Electric Company

All rights reserved

You are allowed to print copies of this tutorial for your personal use, and link to this page, but you are not allowed to make electronic copies, or redistribute this tutorial in any form without permission.

Original version written in 1994 and published in the Sun Observer
Updated: Tue Mar 9 11:07:08 EST 2004
Updated: Fri Feb 16 05:32:38 EST 2007
Updated: Wed Apr 16 20:55:07 EDT 2008

Awk is an extremely versatile programming language for working on files. We'll teach you just enough to understand the examples in this page, plus a smidgen.

The examples given below have the extensions of the executing script as part of the filename. Once you download it, and make it executable, you can rename it anything you want.

Why learn AWK?

In the past I have covered grep and sed. This section discusses AWK, another cornerstone of UNIX shell programming. There are three variations of AWK:

AWK - the original from AT&T
NAWK - A newer, improved version from AT&T
GAWK - The Free Software foundation's version

Originally, I didn't plan to discuss NAWK, but several UNIX vendors have replaced AWK with NAWK, and there are several incompatibilities between the two. It would be cruel of me to not warn you about the differences. So I will highlight those when I come to them. It is important to know than all of AWK's features are in NAWK and GAWK. Most, if not all, of NAWK's features are in GAWK. NAWK ships as part of Solaris. GAWK does not. However, many sites on the Internet have the sources freely available. If you user Linux, you have GAWK. But in general, assume that I am talking about the classic AWK unless otherwise noted.

Why is AWK so important? It is an excellent filter and report writer. Many UNIX utilities generates rows and columns of information. AWK is an excellent tool for processing these rows and columns, and is easier to use AWK than most conventional programming languages. It can be considered to be a pseudo-C interpretor, as it understands the same arithmatic operators as C. AWK also has string manipulation functions, so it can search for particular strings and modify the output. AWK also has associative arrays, which are incredible useful, and is a feature most computing languages lack. Associative arrays can make a complex problem a trivial exercise.

I won't exhaustively cover AWK. That is, I will cover the essential parts, and avoid the many variants of AWK. It might be too confusing to discuss three different versions of AWK. I won't cover the GNU version of AWK called "gawk." Similarly, I will not discuss the new AT&T AWK called "nawk." The new AWK comes on the Sun system, and you may find it superior to the old AWK in many ways. In particular, it has better diagnostics, and won't print out the infamous "bailing out near line ..." message the original AWK is prone to do. Instead, "nawk" prints out the line it didn't understand, and highlights the bad parts with arrows. GAWK does this as well, and this really helps a lot. If you find yourself needing a feature that is very difficult or impossible to do in AWK, I suggest you either use NAWK, or GAWK, or convert your AWK script into PERL using the "a2p" conversion program which comes with PERL. PERL is a marvelous language, and I use it all the time, but I do not plan to cover PERL in these tutorials. Having made my intention clear, I can continue with a clear conscience.

Many UNIX utilities have strange names. AWK is one of those utilities. It is not an abbreviation for awkward. In fact, it is an elegant and simple language. The work "AWK" is derived from the initials of the language's three developers: A. Aho, B. W. Kernighan and P. Weinberger.

Basic Structure

The essential organization of an AWK program follows the form:

pattern { action }

The pattern specifies when the action is performed. Like most UNIX utilities, AWK is line oriented. That is, the pattern specifies a test that is performed with each line read as input. If the condition is true, then the action is taken. The default pattern is something that matches every line. This is the blank or null pattern. Two other important patterns are specified by the keywords "BEGIN" and "END." As you might expect, these two words specify actions to be taken before any lines are read, and after the last line is read. The AWK program below:

BEGIN 	{ print "START" }<br />		{ print }<br />END   	{ print "STOP" }<br /><br /></pre> </dd></dl><p> </p><p>adds one line before and one line after the input file. This isn't very useful, but with a simple change, we can make this into a typical AWK program: </p><dl><dd>BEGIN 	{ print "File\tOwner"," }<br />		{ print $8, "\t", $3}<br />END   	{ print " - DONE -" }<br /> </dd></dl><p> </p><p>I'll improve the script in the next sections, but we'll call it "FileOwner." But let's not put it into a script or file yet. I will cover that part in a bit. Hang on and follow with me so you get the flavor of AWK. </p><p>The characters "\t" Indicates a tab character so the output lines up on even boundries. The "$8" and "$3" have a meaning similar to a shell script. Instead of the eighth and third argument, they mean the eighth and third field of the input line. You can think of a field as a column, and the action you specify operates on each line or row read in. </p><p>There are two differences between AWK and a shell processing the characters within double quotes. AWK understands special characters follow the "\" character like "t". The Bourne and C UNIX shells do not. Also, unlike the shell (and PERL) AWK does not evaluate variables within  strings. To explain, the second line could not be written like this: </p><dl><dd>	{print "$8\t$3" }<br /> </dd></dl><p>That example would print "$8 $3." Inside the quotes, the dollar sign is not a special character. Outside, it corresponds to a field. What do I mean by the third and eight field? Consider the Solaris "/usr/bin/ls -l" command, which  has eight columns of information. The System V version (Similar to the Linux version),  "/usr/5bin/ls -l," has 9 columns. The third column is the owner, and the eighth (or nineth) column in the name of the file. This AWK program can be used to process the output of the "ls -l" command, printing out the filename, then the owner, for each file. I'll show you how. </p><p>Update: On a linux system, change "$8" to "$9". </p><p>One more point about the use of a dollar sign. In scripting languages like Perl and the various shells, a dollar sign means the word following is the name of the variable.  Awk is different. The dollar sign means that we are refering to a field or column in the current line. When switching between Perl and AWK you must remener that "$" has a different meaning. So the following piece of code prints two "fields" to standard out. The first field printed is the number "5", the second is the fifth field (or column) on the input line. </p><dl><dd>BEGIN 	{ x=5 }<br />		{ print x, $x}<br /> </dd></dl><p> </p><h1><a name="uh-2" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-2">Executing an AWK script</a></h1> <p> So let's start writing our first AWK script. There are a couple of ways to do this. </p><p>Assuming the first script is called  "FileOwner," the invocation would be </p><dl><dd>ls -l | FileOwner<br /> </dd></dl><p> </p><p>This might generate the following if there were only two files in the current directory: </p><dl><dd>File	Owner<br /><p><br />a.file	barnett<br />another.file 	 barnett<br /> - DONE -<br /> </p></dd></dl><p>There are two problems with this script. Both problems are easy to fix, but I'll hold off on this until I cover the basics. </p><p>The script itself can be written in many ways. The C shell version would look like this: <br /></p><pre>#!/bin/csh -f<br /># Linux users have to change $8 to $9<br />awk '<br />BEGIN 	{ print "File\tOwner" } \<br />		{ print $8, "\t", $3}	\<br />END   	{ print " - DONE -" } \<br />'<br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example1.csh">awk_example1.csh</a><br /></p><p>As you can see in the above script, each line of the AWK script must  have a backslash if it is not the last line of the script. This is necessary as the C shell doesn't, by default, allow strings I have a long list of complaints about using the C shell. See <a href="http://www.grymoire.com/Unix/CshTop10.txt">Top Ten reasons not to use the C shell</a><br />The Bourne shell (as does most shells) allows quoted strings to span several lines: <br /><br />#!/bin/sh<br /># Linux users have to change $8 to $9 <br />awk '<br />BEGIN 	{ print "File\tOwner" } <br />		{ print $8, "\t", $3}	<br />END   	{ print " - DONE -" } <br />'<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example1.sh">awk_example1.sh</a><br />The third form is to store the commands in a file, and execute </p><dl><dd>awk -f filename<br /> </dd></dl><p>Since AWK is also an interpretor, you can save yourself a step and make the file executable by add one line in the beginning of the file: <br /><br />#!/bin/awk -f<br />BEGIN 	{ print "File\tOwner" }<br />		{ print $8, "\t", $3}<br />END   	{ print " - DONE -" }<br /> <br /><br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example1.awk">awk_example1.awk</a><br /></p><p>Change the permission with the <i>chmod</i> command, (i.e. "chmod +x awk_example1.awk"), and the script becomes a new command. Notice the "-f" option following '#!/bin/awk "above, which is also used in the third format where you use AWK to execute the file directly, i.e. "awk -f filename". The "-f" option specifies the AWK file containing the instructions. As you can see, AWK considers lines that start with a "#" to be a comment, just like the shell. To be precise, anything from the "#" to the end of the line is a comment (unless its inside an AWK string. However, I always comment my AWK scripts with the "#" at the start of the line, for reasons I'll discuss later. </p><p>Which format should you use? I prefer the last format when possible. It's shorter and simpler. It's also easier to debug problems. If you need to use a shell, and want to avoid using too many files, you can  combine them as we did in the first and second example. </p><h1><a name="uh-3" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-3">Which shell to use with AWK?</a></h1><p> </p><p>The format of AWK is not free-form.  You cannot put new line breaks just anywhere. They must go in particular locations. To be precise, in the original AWK you can insert a new line character after the curly braces, and at the end of a command, but not elsewhere. If you wanted to break a long line into two lines at any other place,  you had to use a backslash: <br /><br />#!/bin/awk -f<br />BEGIN 	{ print "File\tOwner" }<br />		{ print $8, "\t", \ <br />		$3} <br />END   	{ print " - DONE -" }<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example2.awk">awk_example2.awk</a><br /></p><p>The Bourne shell version would be <br /><br />#!/bin/sh<br />awk '<br />BEGIN	{ print "File\tOwner" }<br />		{ print $8, "\t", \<br />		$3}<br />END		{ print "done"} <br />'<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example2.sh">awk_example2.sh</a><br /></p><p>while the C shell would be <br /><br />#!/bin/csh -f<br />awk '<br />BEGIN	{ print "File\tOwner" }\<br />		{ print $8, "\t", \\<br />		$3}\<br />END		{ print "done"}\<br />'<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example2.csh">awk_example2.csh</a><br /></p><p>As you can see, this demonstrates how awkward the C shell is when enclosing an AWK script. Not only are back slashes needed for every line, some lines need two. (Note - this is true when using old awk (e.g. on Solaris) because the print statement had to be on one line. Newer AWK's are more flexible where newlines can be added.) Many people will warn you about the C shell. Some of the problems are subtle, and you may never see them. Try to include an AWK or <i>sed</i> script within a C shell script, and the back slashes will drive you crazy. This is what convinced me to learn the Bourne shell years ago, when I was starting out. I strongly recommend you use the Bourne shell for  any AWK or <i>sed</i> script. If you don't use the Bourne shell, then you should learn it.  As a minimum, learn how to set variables, which by some strange coincidence is the subject of the next section.  </p><h1><a name="uh-4" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-4">Dynamic Variables</a></h1><p>Since you can make a script an AWK executable by mentioning "#!/bin/awk -f" on the first line, including an AWK script inside a shell script isn't needed unless you want to either eliminate the need for an extra file,  or if you want to pass a variable to the insides of an AWK script. Since this is a common problem, now is as good a time to explain the technique. I'll do this by showing a simple AWK program that will only print one column. <b>NOTE: there will be a bug in the first version.</b> The number of the column will be specified by the first argument. The first version of the program, which we will call "Column," looks like this: <br /><br />#!/bin/sh<br />#NOTE - this script does not work!<br />column=$1<br />awk '{print $column}'<br /> <br />Click here to get file (but be aware that it doesn't work): <a href="http://www.grymoire.com/Unix/Scripts/Column1.sh">Column1.sh</a><br /></p><p>A suggested use is: </p><dl><dd>ls -l | Column 3<br /> </dd></dl><p> </p><p>This would print the third column from the <i>ls</i> command, which would be the owner of the file.  You can change this into a utility that  counts how many files are owned by each user by adding </p><dl><dd>ls -l | Column 3 | uniq -c | sort -nr<br /> </dd></dl><p> </p><p><b>Only one problem: the script doesn't work.</b> The value of the "column" variable is not seen by AWK. Change "awk" to "echo" to check. You need to turn off the quoting when the variable is seen. This can be done by  ending the quoting, and restarting it after the variable: <br /><br />#!/bin/sh<br />column=$1<br />awk '{print </pre>  <p>Since I've already discussed many of these, I'll only cover those that I missed earlier. </p><h1><a name="uh-56" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-56">ARGC - Number or arguments (NAWK/GAWK)</a></h1><p>The variable <b>ARGC</b> specifies the number of arguments on the command line. It always has the value of one or more, as it counts its own program name as the first argument. If you specify an AWK filename using the "-f" option, it is not counted as an argument. If you include a variable on the command line using the form below, NAWK does not count as an argument. </p><dl><dd>nawk -f file.awk x=17<br /> </dd></dl><p> </p><p>GAWK does, but that is because GAWK requires the  "-v" option before each assignment: </p><dl><dd>gawk -f file.awk -v x=17<br /> </dd></dl><p>GAWK variables initialized this way do not affect the <b>ARGC</b> variable. </p><h1><a name="uh-57" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-57">ARGV - Array of arguments (NAWK/GAWK)</a></h1><p>The  <b>ARGV</b> array is the list of arguments (or files) passed as command line arguments. </p><h1><a name="uh-58" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-58">ARGIND - Argument Index (GAWK only)</a></h1><p>The <b>ARGIND</b> specifies the current index into the  <b>ARGV</b> array, and therefore <b>ARGV[ARGIND]</b> is always the current filename. Therefore </p><dl><dd>FILENAME == ARGV[ARGIND] <br /> </dd></dl><p>is always true. It can be modified, allowing you to skip over files, etc. </p><h1><a name="uh-59" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-59">FNR (NAWK/GAWK)</a></h1><p>The <b>FNR</b> variable contains the number of lines read, but is reset for each file read. The  <b>NR</b> variable accumulates for all files read. Therefore if you execute an awk script with two files as arguments, with each containing 10 lines: </p><dl><dd>nawk '{print NR}' file file2<br />nawk '{print FNR}' file file2<br /> </dd></dl><p> </p><p>the first program would print the numbers 1 through 20, while the second would print the numbers 1 through 10 twice, once for each file. </p><h1><a name="uh-60" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-60">OFMT (NAWK/GAWK)</a></h1><p>The <b>OFMT</b> variable Specifies the default format for numbers. The default value is "%.6g."  </p><h1><a name="uh-61" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-61">RSTART, RLENGTH and match (NAWK/GAWK)</a></h1><p>I've already mentioned the  <b>RSTART</b> and <b>RLENGTH</b> variables. After the <i>match</i>() function is called, these variables contain the location in the string  of the search pattern. <b>RLENGTH</b> contains the length of this match. </p><h1><a name="uh-62" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-62">SUBSEP - Multi-dimensional array separator (NAWK/GAWK)</a></h1><p>Earlier I described how you can construct multi-dimensional arrays in AWK. These are constructed by concatenating two indexes together with a special character between them. If I use an ampersand as the special character, I can access the value at location X, Y by the reference </p><dl><dd>array[ X "&" Y ]<br /> </dd></dl><p>NAWK (and GAWK) has this feature built in. That is, you can specify the array element </p><dl><dd>array[X,Y]<br /> </dd></dl><p>It automatically constructs the string, placing a special character between the indexes. This character is the non-printing character "034." You can control the value of this character, to make sure your  strings do not contain the same character. </p><h1><a name="uh-63" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-63">ENVIRON - environment variables (GAWK only)</a></h1><p>The <b>ENVIRON</b> array contains the environment variables the current process. You can print your current search path using </p><dl><dd>print ENVIRON["PATH"]<br /> </dd></dl><p> </p><h1><a name="uh-64" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-64">IGNORECASE (GAWK only)</a></h1><p>The <b>IGNORECASE</b> variable is normally zero. If you set it to non-zero, then all pattern matches ignore case. Therefore the following is equivalent to  "grep -i match:"  </p><dl><dd>BEGIN {IGNORECASE=1;}<br />/match/ {print}<br /> </dd></dl><p> </p><h1><a name="uh-65" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-65">CONVFMT - conversion format (GAWK only)</a></h1><p>The <b>CONVFMT</b> variable is used to specify the format when converting a number to a string. The default value is "%.6g." One way to truncate integers is to convert an integer to a string, and convert the string to an integer - modifying the actions with <b>CONVFMT</b>:  </p><dl><dd>a = 12;<br />b = a "";<br />CONVFMT = "%2.2f";<br />c = a "";<br /> </dd></dl><p> </p><p>Variables <b>b</b> and <b>c</b> are both strings, but the first one will have the value "12.00" while the second will have the value "12."  </p><h1><a name="uh-66" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-66">ERRNO - system errors (GAWK only)</a></h1><p>The <b>ERRNO</b> variable describes the error, as a string, after a call to the <b>getline</b> command fails.  </p><h1><a name="uh-67" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-67">FIELDWIDTHS - fixed width fields (GAWK only)</a></h1><p>The <b>FIELDWIDTHS</b> variable is used when processing fixed width input. If you wanted to read a file that had 3 columns of data; the first one  is 5 characters wide, the second 4, and the third 7, you could use <i>substr</i> to split the line apart. The technique, using  <b>FIELDWIDTHS</b>, would be: </p><dl><dd>BEGIN {FIELDWIDTHS="5 4 7";}<br />{ printf("The three fields are %s %s %sn", $1, $2, $3);}<br /> </dd></dl><p> </p><p> </p>$column'}'<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/Column2.sh">Column2.sh</a><br /></p><p>This is a very important concept, and throws experienced programmers a curve ball. In many computer languages, a string has a start quote, and end quote,  and the contents in between. If you want to include a special character inside the quote, you must  prevent the character from having the typical meaning.  In the C language, this is down by putting a backslash before the character. In other languages, there is a special combination of characters to to this. In the C and Bourne shell, the quote is just a switch. It turns the interpretation mode on or off. There is really no such concept as  "start of string" and "end of string." The quotes toggle a switch inside the interpretor. The quote character is not passed on to the application. This is why there are two pairs of quotes above. Notice there are two dollar signs. The first one is quoted, and is seen by AWK. The second one is not quoted, so the shell evaluates the variable, and replaces "$column" by the value. If you don't understand, either change "awk" to "echo," or change the first line to read "#!/bin/sh -x."  </p><p>Some improvements are needed, however. The Bourne shell has a mechanism to provide a value for a variable if the value isn't set, or is set and the value is an empty string. This is done by using the format: </p><dl><dd>${<i>variable</i>:-<i>defaultvalue</i>}<br /> </dd></dl><p>This is shown below, where the default column will be one: <br /><br />#!/bin/sh<br />column=${1:-1}<br />awk '{print </pre>  <p>Since I've already discussed many of these, I'll only cover those that I missed earlier. </p><h1><a name="uh-56" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-56">ARGC - Number or arguments (NAWK/GAWK)</a></h1><p>The variable <b>ARGC</b> specifies the number of arguments on the command line. It always has the value of one or more, as it counts its own program name as the first argument. If you specify an AWK filename using the "-f" option, it is not counted as an argument. If you include a variable on the command line using the form below, NAWK does not count as an argument. </p><dl><dd>nawk -f file.awk x=17<br /> </dd></dl><p> </p><p>GAWK does, but that is because GAWK requires the  "-v" option before each assignment: </p><dl><dd>gawk -f file.awk -v x=17<br /> </dd></dl><p>GAWK variables initialized this way do not affect the <b>ARGC</b> variable. </p><h1><a name="uh-57" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-57">ARGV - Array of arguments (NAWK/GAWK)</a></h1><p>The  <b>ARGV</b> array is the list of arguments (or files) passed as command line arguments. </p><h1><a name="uh-58" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-58">ARGIND - Argument Index (GAWK only)</a></h1><p>The <b>ARGIND</b> specifies the current index into the  <b>ARGV</b> array, and therefore <b>ARGV[ARGIND]</b> is always the current filename. Therefore </p><dl><dd>FILENAME == ARGV[ARGIND] <br /> </dd></dl><p>is always true. It can be modified, allowing you to skip over files, etc. </p><h1><a name="uh-59" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-59">FNR (NAWK/GAWK)</a></h1><p>The <b>FNR</b> variable contains the number of lines read, but is reset for each file read. The  <b>NR</b> variable accumulates for all files read. Therefore if you execute an awk script with two files as arguments, with each containing 10 lines: </p><dl><dd>nawk '{print NR}' file file2<br />nawk '{print FNR}' file file2<br /> </dd></dl><p> </p><p>the first program would print the numbers 1 through 20, while the second would print the numbers 1 through 10 twice, once for each file. </p><h1><a name="uh-60" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-60">OFMT (NAWK/GAWK)</a></h1><p>The <b>OFMT</b> variable Specifies the default format for numbers. The default value is "%.6g."  </p><h1><a name="uh-61" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-61">RSTART, RLENGTH and match (NAWK/GAWK)</a></h1><p>I've already mentioned the  <b>RSTART</b> and <b>RLENGTH</b> variables. After the <i>match</i>() function is called, these variables contain the location in the string  of the search pattern. <b>RLENGTH</b> contains the length of this match. </p><h1><a name="uh-62" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-62">SUBSEP - Multi-dimensional array separator (NAWK/GAWK)</a></h1><p>Earlier I described how you can construct multi-dimensional arrays in AWK. These are constructed by concatenating two indexes together with a special character between them. If I use an ampersand as the special character, I can access the value at location X, Y by the reference </p><dl><dd>array[ X "&" Y ]<br /> </dd></dl><p>NAWK (and GAWK) has this feature built in. That is, you can specify the array element </p><dl><dd>array[X,Y]<br /> </dd></dl><p>It automatically constructs the string, placing a special character between the indexes. This character is the non-printing character "034." You can control the value of this character, to make sure your  strings do not contain the same character. </p><h1><a name="uh-63" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-63">ENVIRON - environment variables (GAWK only)</a></h1><p>The <b>ENVIRON</b> array contains the environment variables the current process. You can print your current search path using </p><dl><dd>print ENVIRON["PATH"]<br /> </dd></dl><p> </p><h1><a name="uh-64" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-64">IGNORECASE (GAWK only)</a></h1><p>The <b>IGNORECASE</b> variable is normally zero. If you set it to non-zero, then all pattern matches ignore case. Therefore the following is equivalent to  "grep -i match:"  </p><dl><dd>BEGIN {IGNORECASE=1;}<br />/match/ {print}<br /> </dd></dl><p> </p><h1><a name="uh-65" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-65">CONVFMT - conversion format (GAWK only)</a></h1><p>The <b>CONVFMT</b> variable is used to specify the format when converting a number to a string. The default value is "%.6g." One way to truncate integers is to convert an integer to a string, and convert the string to an integer - modifying the actions with <b>CONVFMT</b>:  </p><dl><dd>a = 12;<br />b = a "";<br />CONVFMT = "%2.2f";<br />c = a "";<br /> </dd></dl><p> </p><p>Variables <b>b</b> and <b>c</b> are both strings, but the first one will have the value "12.00" while the second will have the value "12."  </p><h1><a name="uh-66" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-66">ERRNO - system errors (GAWK only)</a></h1><p>The <b>ERRNO</b> variable describes the error, as a string, after a call to the <b>getline</b> command fails.  </p><h1><a name="uh-67" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-67">FIELDWIDTHS - fixed width fields (GAWK only)</a></h1><p>The <b>FIELDWIDTHS</b> variable is used when processing fixed width input. If you wanted to read a file that had 3 columns of data; the first one  is 5 characters wide, the second 4, and the third 7, you could use <i>substr</i> to split the line apart. The technique, using  <b>FIELDWIDTHS</b>, would be: </p><dl><dd>BEGIN {FIELDWIDTHS="5 4 7";}<br />{ printf("The three fields are %s %s %sn", $1, $2, $3);}<br /> </dd></dl><p> </p><p> </p>$column'}'<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/Column3.sh">Column3.sh</a><br /></p><p>We can save a line by combining these two steps: <br /><br />#!/bin/sh<br />awk '{print </pre>  <p>Since I've already discussed many of these, I'll only cover those that I missed earlier. </p><h1><a name="uh-56" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-56">ARGC - Number or arguments (NAWK/GAWK)</a></h1><p>The variable <b>ARGC</b> specifies the number of arguments on the command line. It always has the value of one or more, as it counts its own program name as the first argument. If you specify an AWK filename using the "-f" option, it is not counted as an argument. If you include a variable on the command line using the form below, NAWK does not count as an argument. </p><dl><dd>nawk -f file.awk x=17<br /> </dd></dl><p> </p><p>GAWK does, but that is because GAWK requires the  "-v" option before each assignment: </p><dl><dd>gawk -f file.awk -v x=17<br /> </dd></dl><p>GAWK variables initialized this way do not affect the <b>ARGC</b> variable. </p><h1><a name="uh-57" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-57">ARGV - Array of arguments (NAWK/GAWK)</a></h1><p>The  <b>ARGV</b> array is the list of arguments (or files) passed as command line arguments. </p><h1><a name="uh-58" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-58">ARGIND - Argument Index (GAWK only)</a></h1><p>The <b>ARGIND</b> specifies the current index into the  <b>ARGV</b> array, and therefore <b>ARGV[ARGIND]</b> is always the current filename. Therefore </p><dl><dd>FILENAME == ARGV[ARGIND] <br /> </dd></dl><p>is always true. It can be modified, allowing you to skip over files, etc. </p><h1><a name="uh-59" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-59">FNR (NAWK/GAWK)</a></h1><p>The <b>FNR</b> variable contains the number of lines read, but is reset for each file read. The  <b>NR</b> variable accumulates for all files read. Therefore if you execute an awk script with two files as arguments, with each containing 10 lines: </p><dl><dd>nawk '{print NR}' file file2<br />nawk '{print FNR}' file file2<br /> </dd></dl><p> </p><p>the first program would print the numbers 1 through 20, while the second would print the numbers 1 through 10 twice, once for each file. </p><h1><a name="uh-60" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-60">OFMT (NAWK/GAWK)</a></h1><p>The <b>OFMT</b> variable Specifies the default format for numbers. The default value is "%.6g."  </p><h1><a name="uh-61" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-61">RSTART, RLENGTH and match (NAWK/GAWK)</a></h1><p>I've already mentioned the  <b>RSTART</b> and <b>RLENGTH</b> variables. After the <i>match</i>() function is called, these variables contain the location in the string  of the search pattern. <b>RLENGTH</b> contains the length of this match. </p><h1><a name="uh-62" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-62">SUBSEP - Multi-dimensional array separator (NAWK/GAWK)</a></h1><p>Earlier I described how you can construct multi-dimensional arrays in AWK. These are constructed by concatenating two indexes together with a special character between them. If I use an ampersand as the special character, I can access the value at location X, Y by the reference </p><dl><dd>array[ X "&" Y ]<br /> </dd></dl><p>NAWK (and GAWK) has this feature built in. That is, you can specify the array element </p><dl><dd>array[X,Y]<br /> </dd></dl><p>It automatically constructs the string, placing a special character between the indexes. This character is the non-printing character "034." You can control the value of this character, to make sure your  strings do not contain the same character. </p><h1><a name="uh-63" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-63">ENVIRON - environment variables (GAWK only)</a></h1><p>The <b>ENVIRON</b> array contains the environment variables the current process. You can print your current search path using </p><dl><dd>print ENVIRON["PATH"]<br /> </dd></dl><p> </p><h1><a name="uh-64" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-64">IGNORECASE (GAWK only)</a></h1><p>The <b>IGNORECASE</b> variable is normally zero. If you set it to non-zero, then all pattern matches ignore case. Therefore the following is equivalent to  "grep -i match:"  </p><dl><dd>BEGIN {IGNORECASE=1;}<br />/match/ {print}<br /> </dd></dl><p> </p><h1><a name="uh-65" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-65">CONVFMT - conversion format (GAWK only)</a></h1><p>The <b>CONVFMT</b> variable is used to specify the format when converting a number to a string. The default value is "%.6g." One way to truncate integers is to convert an integer to a string, and convert the string to an integer - modifying the actions with <b>CONVFMT</b>:  </p><dl><dd>a = 12;<br />b = a "";<br />CONVFMT = "%2.2f";<br />c = a "";<br /> </dd></dl><p> </p><p>Variables <b>b</b> and <b>c</b> are both strings, but the first one will have the value "12.00" while the second will have the value "12."  </p><h1><a name="uh-66" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-66">ERRNO - system errors (GAWK only)</a></h1><p>The <b>ERRNO</b> variable describes the error, as a string, after a call to the <b>getline</b> command fails.  </p><h1><a name="uh-67" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-67">FIELDWIDTHS - fixed width fields (GAWK only)</a></h1><p>The <b>FIELDWIDTHS</b> variable is used when processing fixed width input. If you wanted to read a file that had 3 columns of data; the first one  is 5 characters wide, the second 4, and the third 7, you could use <i>substr</i> to split the line apart. The technique, using  <b>FIELDWIDTHS</b>, would be: </p><dl><dd>BEGIN {FIELDWIDTHS="5 4 7";}<br />{ printf("The three fields are %s %s %sn", $1, $2, $3);}<br /> </dd></dl><p> </p><p> </p>${1:-1}'}'<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/Column4.sh">Column4.sh</a><br /></p><p>It is hard to read, but it is compact. There is one other method that can be used. If you execute an AWK command and include on the command line </p><dl><dd><i>variable</i>=<i>value</i><br /> </dd></dl><p> </p><p>this variable will be set when the AWK script starts. An example of this use would be: <br /><br />#!/bin/sh<br />awk '{print $c}' c=${1:-1}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/Column5.sh">Column5.sh</a><br /></p><p>This last variation does not have the problems with  quoting the previous example had. You should master the earlier example, however, because you can use it with any script or command. The second method is special to AWK. Modern AWK's have other options as well. See the  <a href="http://cfaj.freeshell.org/shell/cus-faq-2.html#24"> comp.unix.shell FAQ</a>.   </p><h1><a name="uh-5" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-5">The Essential Syntax of AWK</a></h1><p>Earlier I discussed ways to start an AWK script. This section will  discuss the various grammatical elements of AWK. </p><h1><a name="uh-6" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-6">Arithmetic Expressions</a></h1><p>There are several arithmetic operators, similar to C. These are the binary  operators,  which operate on two variables: </p><pre>       +--------------------------------------------+<br />       |		AWK Table 1		    |<br />       |	     Binary Operators		    |<br />       |Operator	Type	     Meaning	    |<br />       +--------------------------------------------+<br />       |+		Arithmetic   Addition	    |<br />       |-		Arithmetic   Subtraction    |<br />       |*		Arithmetic   Multiplication |<br />       |/		Arithmetic   Division	    |<br />       |%		Arithmetic   Modulo	    |<br />       |<space>		String	 Concatenation      |<br />       +--------------------------------------------+</pre><p> Using variables with the value of  "7" and "3," AWK returns the following results for each operator when using the print command: </p><pre>                   +---------------------+<br />		   |Expression	 Result	 |<br />		   +---------------------+<br />		   |7+3		 10	 |<br />		   |7-3		 4	 |<br />		   |7*3		 21	 |<br />		   |7/3		 2.33333 |<br />		   |7%3		 1	 |<br />		   |7 3		 73	 |<br />		   +---------------------+</pre>  <p>There are  a few points to make. The modulus operator finds the remainder after an integer divide.  The  <i>print</i> command output a floating point number on the divide, but an integer for the rest.  The string concatenate operator is confusing, since it isn't even visible.  Place a space between two variables and the strings are concatenated together. This also shows that numbers are converted automatically into strings  when needed. Unlike C, AWK doesn't have  "types" of variables. There is one type only, and it can be a string or number.  The conversion rules are simple. A number can easily be converted into a string.  When a string is converted into a number, AWK will do so. The string "123" will be converted into the number 123. However, the string "123X" will be converted into the number 0. (NAWK will behave differently, and converts the string into integer 123, which is found in the beginning of the string). </p><h1><a name="uh-7" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-7">Unary arithmetic operators</a></h1><p>The "+" and "-" operators can be used before variables and numbers. If X equals 4, then the statement: </p><dl><dd>print -x;<br /> </dd></dl><p>will print  "-4."  </p><h1><a name="uh-8" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-8">The Autoincrement and Autodecrement Operators</a></h1><p> </p><p>AWK also supports the "++" and "--" operators of C. Both increment or decrement the variables by one.  The operator can only be used with a single variable, and can be before or after the variable.  The prefix form modifies the value, and then uses the result, while the postfix form gets the results of the variable, and afterwards modifies the variable.  As an example, if X has the value of 3, then the AWK statement </p><dl><dd>print x++, " ", ++x;<br /> </dd></dl><p> </p><p>would print the numbers 3 and 5.  These operators are also assignment operators, and can be used by themselves on a line: </p><dl><dd>x++;<br />--y;<br /> </dd></dl><p> </p><h1><a name="uh-9" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-9">Assignment Operators</a></h1><p>Variables can be assigned new values with the assignment operators. You know about "++" and "--." The other assignment statement is simply: </p><dl><dd><i>variable</i> = <i>arithmetic_expression</i><br /> </dd></dl><p> </p><p>Certain operators have precedence over others; parenthesis can be used to control grouping. The statement </p><dl><dd>x=1+2*3 4;<br /> </dd></dl><p> </p><p>is the same as </p><dl><dd>x = (1 + (2 * 3))  "4";<br /> </dd></dl><p> </p><p>Both print out  "74."  </p><p>Notice spaces can be added for readability. AWK, like C, has special assignment operators, which combine a calculation with an assignment. Instead of saying </p><dl><dd>x=x+2;<br /> </dd></dl><p> </p><p>you can more concisely say: </p><dl><dd>x+=2;<br /> </dd></dl><p> </p><p>The complete list follows: </p><pre>         +-----------------------------------------+<br />	 |		AWK Table 2		   |<br />	 |	    Assignment Operators	   |<br />	 |Operator   Meaning			   |<br />	 |+=	     Add result to variable	   |<br />	 |-=	     Subtract result from variable |<br />	 |*=	     Multiply variable by result   |<br />	 |/=	     Divide variable by result	   |<br />	 |%=	     Apply modulo to variable	   |<br />	 +-----------------------------------------+</pre>  <h1><a name="uh-10" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-10">Conditional expressions</a></h1><p>The second type of expression in AWK is the conditional expression. This is used for certain tests, like the  <i>if</i> or <i>while</i>. Boolean conditions evaluate to true or false.  In AWK, there is a definite difference between a boolean condition, and an arithmetic expression.  You cannot convert a boolean condition to an integer or string.  You can, however, use an arithmetic expression as a conditional expression. A value of 0 is false, while anything else is true. Undefined variables has the value of 0. Unlike AWK, NAWK lets you use booleans as integers. </p><p>Arithmetic values can also be converted into boolean conditions by using relational operators: </p><pre>          +---------------------------------------+<br />	  |		AWK Table 3		  |<br />	  |	    Relational Operators	  |<br />	  |Operator   Meaning			  |<br />	  +---------------------------------------+<br />	  |==	      Is equal			  |<br />	  |!=	      Is not equal to		  |<br />	  |>	      Is greater than		  |<br />	  |>=      Is greater than or equal to    |<br />	  |<	      Is less than		  |<br />	  |<=      Is less than or equal to	  |<br />	  +---------------------------------------+</pre>  <p>These operators are the same as the C operators. They can be used to compare numbers or strings. With respect to strings, lower case letters are greater than upper case letters. </p><h1><a name="uh-11" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-11">Regular Expressions</a></h1><p>Two operators are used to compare strings to regular expressions: </p><pre>               +-----------------------------+<br />	       |	AWK Table 4	     |<br />	       |Regular Expression Operators |<br />	       |Operator     Meaning	     |<br />	       +-----------------------------+<br />	       |~	     Matches	     |<br />	       |!~	     Doesn't match   |<br />	       +-----------------------------+</pre>  <p>The order in this case is particular. The regular expression must be enclosed by slashes, and comes after the operator.  AWK supports extended regular expressions, so the following are examples of valid tests: </p><dl><dd>word !~ /START/<br />lawrence_welk ~ /(one|two|three)/<br /> </dd></dl><p> </p><h1><a name="uh-12" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-12">And/Or/Not</a></h1><p>There are two boolean operators that can be used with conditional expressions. That is, you can combine two conditional expressions with the "or" or "and" operators: "&&" and "||." There is also the unary not operator: "!."  </p><h1><a name="uh-13" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-13">Commands</a></h1><p>There are only a few commands in AWK. The list and syntax follows: </p><dl><dd>if ( <i>conditional</i> ) <i>statement</i> [ else <i>statement</i> ]<br />while ( <i>conditional</i> ) <i>statement</i><br />for ( <i>expression</i> ; <i>conditional</i> ; <i>expression</i> ) <i>statement</i><br />for ( <i>variable</i> in <i>array</i> ) <i>statement</i><br />break<br />continue<br />{ [ <i>statement</i> ] ...}<br /><i>variable</i>=<i>expression</i><br />print [ <i>expression-list</i> ] [ > <i>expression</i> ]<br />printf <i>format</i> [ , <i>expression-list</i> ] [ > <i>expression</i> ]<br />next <br />exit<br /> </dd></dl><p> </p><p>At this point, you can use AWK as a language for simple calculations; If you wanted to calculate something, and not read any lines for input, you could use the  <i>BEGIN</i> keyword discussed earlier, combined with a <i>exit</i> command: </p><pre>#!/bin/awk -f<br />BEGIN {<br /><br /># Print the squares from 1 to 10 the first way<br /><br />	i=1;<br />	while (i <= 10) {<br />		printf "The square of ", i, " is ", i*i;<br />		i = i+1;<br />	}<br /><br /># do it again, using more concise code<br /><br />	for (i=1; i <= 10; i++) {<br />		printf "The square of ", i, " is ", i*i;<br />	}<br /><br /># now end<br />exit;<br />}<br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_print_squares.awk">awk_print_squares.awk</a><br />The following asks for a number, and then squares it: </p><pre>#!/bin/awk -f<br />BEGIN {<br />    print "type a number";<br />}<br />{<br />    print "The square of ", $1, " is ", $1*$1;<br />    print "type another number";<br />}<br />END {<br />    print "Done"<br />}<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_ask_for_square.awk">awk_ask_for_square.awk</a><br /></p><p>The above isn't a good filter, because it asks for input each time. If you pipe the output of another program into it, you would generate a lot of meaningless prompts. </p><p>Here is a filter that you should find useful. It counts lines, totals up the numbers in the first column, and calculates the average. Pipe "wc -c *" into it, and it will count files, and tell you the average number of words per file, as well as the total words and the number of files. </p><pre>#!/bin/awk -f<br />BEGIN {<br /># How many lines<br />    lines=0;<br />    total=0;<br />}<br />{<br /># this code is executed once for each line<br /># increase the number of files<br />    lines++;<br /># increase the total size, which is field #1<br />    total+=$1;<br />}<br />END {<br /># end, now output the total<br />    print lines " lines read";<br />    print "total is ", total;<br />    if (lines > 0 ) {<br />	print "average is ", total/lines;<br />    } else {<br />	print "average is 0";<br />    }<br />}<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/average.awk">average.awk</a><br /></p><p>You can pipe the output of  "ls -s" into this filter to count the number of files, the total size, and the average size. There is a slight problem with this script, as it includes the output of  "ls" that reports the total.  This causes the number of files to be off by one. Changing </p><dl><dd>lines++;<br /> </dd></dl><p>to </p><dl><dd>if ($1 != "total" ) lines++;<br /> </dd></dl><p> </p><p>will fix this problem. Note the code which prevents a divide by zero. This is common in well-written scripts.  I also initialize the variables to zero. This is not necessary, but it is a good habit. </p><h1><a name="uh-14" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-14">AWK Built-in Variables</a></h1><p> </p><p>I have mentioned two kinds of variables: positional and user defined. A user defined variable is one you create. A positional variable is not a special variable, but a function triggered by the dollar sign. Therefore </p><dl><dd>	print $1;<br /> </dd></dl><p> </p><p>and </p><dl><dd>	X=1;<br />	print $X;<br /> </dd></dl><p> </p><p>do the same thing: print the first field on the line. There are two more points about positional variables that are very useful. The variable "$0" refers to the entire line that AWK reads in. That is, if you had eight fields in a line, </p><dl><dd>	print $0;<br /> </dd></dl><p> </p><p>is similar to  </p><dl><dd>	print $1, $2, $3, $4, $5, $6, $7, $8<br /> </dd></dl><p> </p><p>This will change the spacing between the fields; otherwise, they behave the same. You can modify positional variables. The following commands </p><dl><dd>	$2="";<br />	print;<br /> </dd></dl><p> </p><p>deletes the second field. If you had four fields, and wanted to print out the second and fourth field, there are two ways. This is the first: </p><dl><dd>#!/bin/awk -f<br />{<br />	$1="";<br />	$3="";<br />	print;<br />}<br /> </dd></dl><p> </p><p>and the second </p><dl><dd><p><br />#!/bin/awk -f<br />{<br />	print $2, $4;<br />}<br /> </p></dd></dl><p> </p><p>These perform similarly, but not identically. The number of spaces between the values vary. There are two reasons for this. The actual number of fields does not change. Setting a positional variable to an empty string does not delete the variable. It's still there, but the contents has been deleted. The other reason is the way AWK outputs the entire line. There is a field separator that specifies what character  to put between the fields on output. The first example outputs four fields, while the second outputs two. In-between each field is a space. This is easier to explain if the characters between fields could be modified to be made more visible.  Well, it can. AWK provides special variables for just that purpose. </p><h1><a name="uh-15" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-15">FS - The Input Field Separator Variable</a></h1><p>AWK can be used to parse many system administration files. However, many of these files do not have whitespace as a separator. as an example, the password file uses colons. You can easily change the field separator character to be a colon using the  "-F" command line option.  The following command will print out accounts that don't have passwords: </p><dl><dd>awk -F: '{if ($2 == "") print $1 ": no password!"}' </etc/passwd<br /> </dd></dl><p> </p><p>There is a way to do this without the command line option. The variable "FS" can be set like any variable, and has the same function as the "-F" command line option. The following is a script that has the same function as the one above. </p><pre>#!/bin/awk -f<br />BEGIN {<br />	FS=":";<br />}<br />{<br />	if ( $2 == "" ) {<br />		print $1 ": no password!";<br />	}<br />}<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_nopasswd.awk">awk_nopasswd.awk</a><br /></p><p>The second form can be used to create a UNIX utility, which I will name "chkpasswd," and executed like this: </p><dl><dd>chkpasswd </etc/passwd<br /> </dd></dl><p> </p><p>The command "chkpasswd -F:" cannot be used, because AWK will never see this argument. All interpreter scripts accept one and only one argument, which is immediately after the  "#!/bin/awk" string. In this case, the single argument is "-f." Another difference between the command line option and the internal variable is the ability to set the input field separator to be more than one character. If you specify </p><dl><dd>FS=":  ";<br /> </dd></dl><p> </p><p>then AWK will split a line into fields wherever it sees those two characters,  in that exact order. You cannot do this on the command line. </p><p>There is a third advantage the internal variable has over  the command line option: you can change the field separator character as many times as you want while reading a file. Well, at most once for each line.  You can even change it depending on the line you read. Suppose you had the following file which contains the numbers 1 through 7 in three different formats. Lines 4 through 6  have colon separated fields, while the others separated by spaces. </p><dl><dd>ONE 1 I<br />TWO 2 II<br />#START<br />THREE:3:III<br />FOUR:4:IV<br />FIVE:5:V<br />#STOP<br />SIX 6 VI<br />SEVEN 7 VII<br /> </dd></dl><p> </p><p>The AWK program can easily switch between these formats: </p><pre>#!/bin/awk -f<br />{<br />	if ($1 == "#START") {<br />		FS=":";<br />	} else if ($1 == "#STOP") {<br />		FS=" ";<br />	} else {<br />		#print the Roman number in column 3<br />		print $3<br />	}<br />}<br /><br /></pre> <p>  <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example3.awk">awk_example3.awk</a><br /></p><p>Note the field separator variable retains its value until it  is explicitly changed.  You don't have to reset it for each line. Sounds simple, right? However, I have a trick question for you. What happens if you change the field separator while reading a line? That is, suppose you had the following line </p><dl><dd>One Two:Three:4 Five<br /> </dd></dl><p> </p><p>and you executed the following script: </p><dl><dd>#!/bin/awk -f<br />{<br />	print $2<br />	FS=":"<br />	print $2<br />}<br /> </dd></dl><p> </p><p>What would be printed?  "Three" or  "Two:Three:4?" Well, the script would print out "Two:Three:4" twice. However, if you deleted the first print statement, it would print out "Three" once! I thought this was very strange at first, but after pulling out some hair, kicking the deck, and yelling at muself and everyone who had anything to do with the development of UNIX, it is intuitively obvious.  You just have to be thinking like a professional programmer to realize it is intuitive. I shall explain, and prevent you from  causing yourself physical harm. </p><p>If you change the field separator  <b>before</b> you read the line, the change  <b>affects</b> what you read. If you change it  <b>after</b> you read the line, it will  <b>not</b> redefine the variables. You wouldn't want a variable to change on you  as a side-effect of another action. A programming language with hidden side effects is broken, and should not be trusted. AWK allows you to redefine the field separator either before or after you read the line, and does the right thing each time. Once you read the variable, the variable will not change unless you change it. Bravo! </p><p>To illustrate this further, here is another version of the  previous code that changes the field separator dynamically.  In this case, AWK does it by examining field  "$0," which is the entire line. When the line contains a colon, the field separator is a colon, otherwise, it is a space: </p><pre>#!/bin/awk -f<br />{<br />	if ( $0 ~ /:/ ) {<br />		FS=":";<br />	} else {<br />		FS=" ";<br />	}<br />	#print the third field, whatever format<br />	print $3<br />}<br /><br /></pre> <p>  <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example4.awk">awk_example4.awk</a><br /></p><p>This example eliminates the need to have the special  "#START" and "#STOP" lines in the input. </p><h1><a name="uh-16" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-16">OFS - The Output Field Separator Variable</a></h1><p>There is an important difference between </p><dl><dd>print $2 $3<br /> </dd></dl><p> </p><p>and </p><dl><dd>print $2, $3<br /> </dd></dl><p> </p><p>The first example prints out one field, and the second prints out two fields. In the first case, the two positional parameters are concatenated together and output without a space. In the second case, AWK prints two fields, and  places the output field separator between them.  Normally this is a space, but you can change this by modifying the variable "OFS."  </p><p>If you wanted to copy the password file, but delete the encrypted password, you could use AWK: <br /><br />#!/bin/awk -f<br />BEGIN {<br />	FS=":";<br />	OFS=":";<br />}<br />{<br />	$2="";<br />	print<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/delete_passwd.awk">delete_passwd.awk</a><br /></p><p>Give this script the password file, and it will delete the password, but leave everything else the same. You can make the output field separator any number of characters. You are not limited to a single character. </p><h1><a name="uh-17" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-17">NF - The Number of Fields Variable</a></h1><p> </p><p>It is useful to know how many fields are on a line. You may want to have your script change its operation based on the number of fields. As an example, the command  "ls -l" may generate eight or nine fields, depending on which version you are executing. The System V version, "/usr/bin/ls -l" generates nine fields, which is equivalent to the Berkeley "/usr/ucb/ls -lg" command. If you wanted to print the owner and filename then the following AWK script would work with either version of  "ls:"  <br /><br />#!/bin/awk -f<br /># parse the output of "ls -l"<br /># print owner and filename<br /># remember - Berkeley ls -l has 8 fields, System V has 9<br />{<br />	if (NF == 8) {<br />		print $3, $8;<br />	} else if (NF == 9) {<br />		print $3, $9;<br />	} <br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/owner_group.awk">owner_group.awk</a><br /></p><p>Don't forget the variable can be prepended with a  "$." This allows you to print the last field of any column <br /><br />#!/bin/awk -f<br />{ print $NF; }<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/print_last_field.awk">print_last_field.awk</a><br /></p><p>One warning about AWK. There is a limit of 99 fields in a single line. PERL does not have any such limitations. </p><h1><a name="uh-18" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-18">NR - The Number of Records Variable</a></h1><p> </p><p>Another useful variable is  "NR." This tells you the number of records, or the line number. You can use AWK to only examine certain lines. This example prints lines after the first 100 lines, and puts a line number before each line after 100: <br /><br />#!/bin/awk -f<br />{ if (NR >= 100) {<br />	print NR, $0;<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example5.awk">awk_example5.awk</a><br /></p><h1><a name="uh-19" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-19">RS - The Record Separator Variable</a></h1><p> </p><p>Normally, AWK reads one line at a time, and breaks up the line into fields. You can set the  "RS" variable to change AWK's definition of a  "line." If you set it to an empty string, then AWK will read the entire file into memory. You can combine this with changing the  "FS" variable. This example treats each line as a field, and prints out the second and third line: </p><pre>#!/bin/awk -f<br />BEGIN {<br /># change the record separator from newline to nothing	<br />	RS=""<br /># change the field separator from whitespace to newline<br />	FS="n"<br />}<br />{<br /># print the second and third line of the file<br />	print $2, $3;<br />}<br /></pre> <pre>#!/bin/awk -f<br /># reports which file is being read<br />BEGIN {<br />	f="";<br />}<br />{	if (f != FILENAME) {<br />		print "reading", FILENAME;<br />		f=FILENAME;<br />	}<br />	print;<br />}<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example6.awk">awk_example6.awk</a><br /></p><p>The two lines are printed with a space between. Also this will only work if the input file is less than 100 lines, therefore this technique is limited. You can use it to  break words up, one word per line, using this: <br /><br />#!/bin/awk -f<br />BEGIN {<br />	RS=" ";<br />}<br />{<br />	print ;<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/oneword_per_line.awk">oneword_per_line.awk</a><br /></p><p>but this only works if all of the words are separated by a space. If there is a tab or punctuation inside, it would not. </p><h1><a name="uh-20" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-20">ORS - The Record Separator Variable</a></h1><p> </p><p>The default output record separator is a newline, like the input. This can be set to be a newline and carriage return, if you need to generate a text file for a non-UNIX system. <br /><br />#!/bin/awk -f<br /># this filter adds a carriage return to all lines<br /># before the newline character<br />BEGIN {	<br />	ORS="rn"<br />}<br />{ print }<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/add_cr.awk">add_cr.awk</a><br /></p><h1><a name="uh-21" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-21">FILENAME - The Current Filename Variable"</a></h1><p> </p><p>The last variable known to regular AWK is "FILENAME," which tells you the name of the file being read. <br /><br />#!/bin/awk -f<br />BEGIN {<br /># change the record separator from newline to nothing	<br />	RS=""<br /># change the field separator from whitespace to newline<br />	FS="n"<br />}<br />{<br /># print the second and third line of the file<br />	print $2, $3;<br />}<br />.)l<br />#!/bin/awk -f<br /># reports which file is being read<br />BEGIN {<br />	f="";<br />}<br />{	if (f != FILENAME) {<br />		print "reading", FILENAME;<br />		f=FILENAME;<br />	}<br />	print;<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example6.awk">awk_example6.awk</a><br /></p><p>This can be used if several files need to be parsed by AWK. Normally you use standard input to provide AWK with information. You can also specify the filenames on the command line. If the above script was called  "testfilter," and if you executed it with </p><dl><dd>testfilter file1 file2 file3<br /> </dd></dl><p>It would print out the filename before  each change. An alternate way to specify this on the command line is </p><dl><dd>testfilter file1 - file3 <file2<br /> </dd></dl><p> </p><p>In this case, the second file will be called "-," which is the conventional name for standard input. I have used this when I want to put some information before and after a filter operation. The prefix and postfix files special data before and after the real data. By checking the filename, you can parse the information differently. This is also useful to report syntax errors in particular files: </p><pre>#!/bin/awk -f<br />{ <br />    if (NF == 6) {<br />        # do the right thing<br />    } else {<br />        if (FILENAME == "-" ) {<br />            print "SYNTAX ERROR, Wrong number of fields,", <br />            "in STDIN, line #:", NR,  "line: ", $0;<br />        } else {<br />            print "SYNTAX ERROR, Wrong number of fields,", <br />            "Filename: ", FILENAME, "line # ", NR,"line: ", $0;<br />        }<br />    }<br />}<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example7.awk">awk_example7.awk</a><br /></p><h1><a name="uh-22" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-22">Associative Arrays</a></h1><p> </p><p>I have used dozens of different programming languages over the last 20 years, and AWK is the first language I found that has associative arrays. This term may be meaningless to you, but believe me, these arrays are invaluable, and simplify programming enormously. Let me describe a problem, and show you how associative arrays can be used for reduce coding time, giving you more time to explore another stupid problem you don't want to deal with in the first place. </p><p>Let's suppose you have a directory overflowing with files, and you want to  find out how many files are owned by each user, and perhaps  how much disk space each user owns.  You really want someone to blame; it's hard to tell who owns what file. A filter that processes the output of  <i>ls</i> would work: </p><dl><dd>ls -l | filter<br /> </dd></dl><p> </p><p>But this doesn't tell you how much space each user is using. It also doesn't work for a large directory tree. This requires <i>find</i> and <i>xargs</i>:  </p><dl><dd>find . -type f -print | xargs ls -l | filter<br /> </dd></dl><p> </p><p>The third column of "ls" is the username. The filter has to count how many times it sees each user. The typical program would have an array of usernames and another array that counts how many times each username has been seen. The index to both arrays are the same; you use one array to find the index, and the second to keep track of the count. I'll show you one way to do it in AWK--the wrong way: </p><pre>#!/bin/awk -f<br /># bad example of AWK programming<br /># this counts how many files each user owns.<br />BEGIN {<br />	number_of_users=0;<br />}<br />{<br /># must make sure you only examine lines with 8 or more fields<br />	if (NF>7) {<br />		user=0;<br /># look for the user in our list of users<br />		for (i=1; i<=number_of_users; i++) {<br />#		is the user known?<br />			if (username[i] == $3) {<br /># found it - remember where the user is<br />				user=i;<br />			}<br />		}<br />		if (user == 0) {<br /># found a new user<br />			username[++number_of_users]=$3;<br />			user=number_of_users;<br />		}<br /># increase number of counts<br />		count[user]++;<br />	}<br />}<br />END {<br />	for (i=1; i<=number_of_users; i++) {<br />		print count[i], username[i]<br />	}<br />}<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example8.awk">awk_example8.awk</a><br /></p><p>I don't want you to <b>read</b> this script. I told you it's the wrong way to do it. If you were a C programmer, and didn't know AWK, you would probably use a technique like the one above. Here is the same program, except this example that uses AWK's  associative arrays. The important point is to notice the difference in size between these two versions: <br /><br />#!/bin/awk -f<br />{<br />	username[$3]++;<br />}<br />END {<br />	for (i in username) {<br />		print username[i], i;<br />	}<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/count_users0.awk">count_users0.awk</a><br /></p><p>This is shorter, simpler, and  <i>much</i> easier to understand--Once you understand exactly what an associative array is. The concept is simple. Instead of using a number to find an entry in an array, use  <i>anything you want</i>. An associative array in an array whose index is a string. All arrays in AWK are associative. In this case, the index into the array is the third field of the "ls" command, which is the username. If the user is  "bin," the main loop increments the count per user by effectively executing </p><dl><dd>	username["bin"]++;<br /> </dd></dl><p> </p><p>UNIX guru's may gleefully report that the 8 line AWK script can be replaced by: </p><dl><dd>awk '{print $3}' | sort | uniq -c | sort -nr<br /> </dd></dl><p>True, However, this can't count the total disk space for each user. We need to add some more intelligence to the AWK script, and need the right foundation to proceed. There is also a slight bug in the AWK program. If you wanted a  "quick and dirty" solution, the above would be fine. If you wanted to make it more robust, you have to handle unusual conditions. If you gave this program an empty file for input, you would get the error: </p><dl><dd>awk: username is not an array<br /> </dd></dl><p>Also, if you piped the output of "ls -l" to it, the line that specified the total would increment a non-existing user. There are two techniques used to eliminate this error. The first one only counts valid input: </p><pre>#!/bin/awk -f<br />{<br />	if (NF>7) {<br />		username[$3]++;<br />	}<br />}<br />END {<br />	for (i in username) {<br />		print username[i], i;<br />	}<br />}<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/count_users1.awk">count_users1.awk</a><br />This fixes the problem of counting the line with the total. However, it still generates an error when an empty file is read as input. To fix this problem, a common technique is to  make sure the array always exists, and has a special marker value which specifies that the entry is invalid. Then when reporting the results, ignore the invalid entry. </p><pre>#!/bin/awk -f<br />BEGIN {<br />	username[""]=0;<br />}<br />{<br />	username[$3]++;<br />}<br />END {<br />	for (i in username) {<br />		if (i != "") {<br />			print username[i], i;<br />		}<br />	}<br />}<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/count_users2.awk">count_users2.awk</a><br /></p><p>This happens to fix the other problem. Apply this technique and you will make your AWK programs more robust and easier for others to use. </p><h1><a name="uh-23" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-23">Multi-dimensional Arrays</a></h1><p>Some people ask if AWK can handle multi-dimensional arrays. It can. However, you don't use conventional two-dimensional arrays. Instead you use associative arrays. (Did I even mention how useful associative arrays are?) Remember, you can put <b>anything</b> in the index of an associative array. It requires a different way to think about problems, but once you understand, you won't be able to live without it. All you have to do is to create an index that combines two other indices. Suppose you wanted to effectively execute </p><dl><dd>	a[1,2] = y;<br /> </dd></dl><p> </p><p>This is invalid in AWK. However, the following is perfectly fine: </p><dl><dd>	a[1 "," 2] = y;<br /> </dd></dl><p>Remember: the AWK string concatenation operator is the space. It combines the three strings into the single string "1,2." Then it uses it as an index into the array. That's all there is to it. There is one minor problem with associative arrays, especially if you use the <i>for</i> command to output each element: you have no control over the order of output. You can create an algorithm to generate the indices to an associative array, and control the order this way. However, this is difficult to do. Since UNIX provides an excellent sort utility, more programmers separate the information processing from the sorting. I'll show you what I mean. </p><h1><a name="uh-24" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-24">Example of using AWK's Associative Arrays</a></h1><p> </p><p>I often find myself using certain techniques repeatedly in AWK. This example will demonstrate these techniques, and illustrate the power and elegance of AWK. The program is simple and common.  The disk is full. Who's gonna be blamed? I just hope you use this power wisely. Remember, you may be the one who filled up the disk. </p><p>Having resolved my moral dilemma, by placing the burden squarely on your  shoulders, I will describe the program in detail. I will also discuss several tips you will find useful in large AWK programs. First, initialize all arrays used in a  <i>for</i> loop.  There will be four arrays for this purpose. Initialization is easy: </p><dl><dd>u_count[""]=0;<br />g_count[""]=0;<br />ug_count[""]=0;<br />all_count[""]=0;<br /> </dd></dl><p>The second tip is to pick a convention for arrays. Selecting the names of the arrays, and the indices for each array is very important. In a complex program,  it can become confusing to remember which array contains what. I suggest you clearly identify the indices and contents of each array. To demonstrate, I will use a "_count" to indicate the number of files, and "_sum" to indicate the sum of the file sizes. In addition, the part before the  "_" specifies the index used for the array, which will be either "u" for user, "g" for group, "ug" for the user and group combination, and "all" for the total for all files. In other programs, I have used names like </p><dl><dd>username_to_directory[username]=directory;<br /> </dd></dl><p>Follow a convention like this, and it will be hard for you to forget the purpose of each associative array. Even when a quick hack comes back to haunt you three years later. I've been there. </p><p>The third suggestion is to make sure your input is in the correct form. It's generally a  good idea to be pessimistic, but I will add a simple but sufficient test in this example. </p><dl><dd>if (NF != 10) {<br />#	ignore<br />} else {<br /><i>etc.</i><br /> </dd></dl><p> </p><p>I placed the test and error clause up front, so the rest of the code won't be cluttered. AWK doesn't have user defined functions. NAWK, GAWK and PERL do. </p><p>The next piece of advice for complex AWK scripts is to define a name for each field used. In this case, we want the user, group and size in disk blocks. We could use the file size in bytes, but the block size corresponds to the blocks on the disk, a more accurate measurement of space. Disk blocks can be found by using "ls -s." This adds a column, so the username becomes the fourth column, etc. Therefore the script will contain: </p><dl><dd>size=$1;<br />user=$4;<br />group=$5; <br /> </dd></dl><p> </p><p>This will allow us to easily adapt to changes in input. We could use "$1" throughout the script, but if we changed the number of fields, which the "-s" option does, we'd have to change each field reference. You don't want to go through an AWK script, and change all the "$1" to  "$2," and also change the  "$2" to "$3" because those are really the "$1" that you just changed to "$2." Of  <b>course</b> this is confusing. That's why it's a good idea to assign names to the fields. I've been there too. </p><p>Next the AWK script will count how many times each combination of users  and groups occur. That is, I am going to construct a two-part index that contains the username and groupname. This will let me count up the number of times each user/group combination occurs, and how much disk space is used. </p><p>Consider this: how would you calculate the total for just a user, or for just a group? You could rewrite the script. Or you could take the user/group totals, and total them with a second script.  </p><p>You could do it, but it's not the AWK way to do it. If you had to examine a bazillion files, and it takes a long time to run that script, it would be a waste to repeat this task. It's also inefficient to require two scripts when one can do everything. The proper way to solve this problem is to extract as much information as possible in one pass through the files. Therefore this script will find the number and size for each category: </p><dl><dd>Each user<br />Each group<br />Each user/group combination<br />All users and groups<br /> </dd></dl><p>This is why I have 4 arrays to count up the number of files. I don't really need 4 arrays, as I can use the format of the index to determine which array is which. But this does maake the program easier to understand for now. The next tip is subtle, but  you will see how useful it is. I mentioned the indices into the array can be anything. If possible, select a format that allows you to merge information from several arrays. I realize this makes no sense right now, but hang in there. All will become clear soon. I will do this by constructing a universal index of the form </p><dl><dd><user> <group><br /> </dd></dl><p> </p><p>This index will be used for all arrays. There is a space between the two values. This covers the total for the user/group combination. What about the other three arrays? I will use a "*" to indicate the total for all users or groups. Therefore the index for all files would be "* *" while the index for all of the file owned by user <i>daemon</i> would be "daemon *." The heart of the script totals up the number and size of each file, putting the information into the right category. I will use 8 arrays; 4 for file sizes, and 4 for counts: </p><dl><dd>u_count[user " *"]++;<br />g_count["* " group]++;<br />ug_count[user " " group]++;<br />all_count["* *"]++;<br /><p><br />u_size[user " *"]+=size;<br />g_size["* " group]+=size;<br />ug_size[user " " group]+=size;<br />all_size["* *"]+=size;<br /> </p></dd></dl><p> </p><p>This particular universal index will make sorting easier, as you will see. Also important is to sort the information in an order that is useful. You can  <b>try</b> to force a particular output order in AWK, but why work at this, when it's a one line command for  <i>sort</i>? The difficult part is finding the right way to sort the information. This script will sort information using the size of the category as the first sort field. The largest total will be the one for all files, so this will be one of the first lines output. However, there may be several ties for the largest number, and  care must be used.  The second field will be the number of files. This will help break a tie. Still, I want the totals and sub-totals to be listed before the individual user/group combinations. The third and fourth fields will be generated by the index of the array. This is the tricky part I warned you about. The script will output one  string, but the  <i>sort</i> utility will not know this. Instead, it will treat it as two fields. This will unify the results, and information from all 4 arrays will look like one array. The sort of the third and fourth fields will be dictionary order, and not numeric,  unlike the first two fields. The  "*" was used so these sub-total fields will be listed before the individual user/group combination. </p><p> The arrays will be printed using the following format: </p><dl><dd>for (i in u_count) {<br />	if (i != "") {<br />       	        print u_size[i], u_count[i], i;<br />	}<br />}<br /> </dd></dl><p> </p><p>I only showed you one array, but all four are printed the same way. That's the essence of the script. The results is sorted, and I converted the space into a tab for cosmetic reasons. </p><h1><a name="uh-25" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-25">Output of the script</a></h1><p>I changed my directory to  <i>/usr/ucb</i>, used the script in that directory. The following is the output: </p><pre>size   count   user   group<br />3173   81      *      *<br />3173   81      root   *<br />2973   75      *      staff<br />2973   75      root   staff<br />88     3       *      daemon<br />88     3       root   daemon<br />64     2       *      kmem<br />64     2       root   kmem<br />48     1       *      tty<br />48     1       root   tty</pre>  <p>This says there are 81 files in this directory, which takes up 3173 disk blocks. All of the files are owned by root. 2973 disk blocks belong to group staff. There are 3 files with group daemon, which takes up 88 disk blocks. </p><p>As you can see, the first line of information is the total for all users and groups. The second line is the sub-total for the user "root." The third line is the sub-total for the group "staff." Therefore the order of the sort is useful, with the sub-totals before the individual entries. You could write a simple AWK or grep script to obtain information from just one user or one group, and the information will be easy to sort. </p><p>There is only one problem. The <i>/usr/ucb</i> directory on my system only uses 1849 blocks; at least that's what <i>du</i> reports.  Where's the discrepancy? The script does  <b>not</b> understand hard links. This may not be a problem on most disks, because many users do not use hard links. Still, it does generate inaccurate results. In this case, the program <i>vi</i> is also <i>e</i>,  <i>ex</i>,  <i>edit</i>,  <i>view</i>, and 2 other names. The program only exists once, but has 7 names. You can tell because the link count (field 2) reports 7. This causes the file to be counted 7 times, which causes an inaccurate total. The fix is to only count multiple links once. Examining the link count will determine if a file has multiple links. However, how can you prevent counting a link twice? There is an easy solution: all of these files have the same  <i>inode</i> number. You can find this number with the <i>-i</i> option to <i>ls</i>. To save memory, we only have to remember the inodes of files that have multiple links. This means we have to add another column to the input, and have to renumber all of the field references. It's a good thing there are only three. Adding a new field will be easy, because I followed my own advice. </p><p>The final script should be easy to follow. I have used variations of this hundreds of times and find it demonstrates the power of AWK as well as provide insight  to a powerful programming paradigm. AWK solves these types of problems easier than most languages. But you have to use AWK the right way. </p><p>This is a fully working version of the program, that accurately counts disk space, appears below:  </p><pre>#!/bin/sh<br />find . -type f -print | xargs /usr/bin/ls -islg | <br />awk '<br />BEGIN {<br /># initialize all arrays used in for loop<br />	u_count[""]=0;<br />	g_count[""]=0;<br />	ug_count[""]=0;<br />	all_count[""]=0;<br />}<br />{<br /># validate your input<br />        if (NF != 11) {<br />#	ignore<br />	} else {<br /># assign field names<br />		inode=$1;<br />		size=$2;<br />		linkcount=$4;<br />		user=$5;<br />		group=$6; <br /><br /># should I count this file?<br /><br />		doit=0;<br />		if (linkcount == 1) {<br /># only one copy - count it<br />			doit++;<br />		} else {<br /># a hard link - only count first one<br />			seen[inode]++;<br />			if (seen[inode] == 1) {<br />				doit++;<br />			}<br />		}<br /># if doit is true, then count the file<br />		if (doit ) {<br /><br /># total up counts in one pass<br /># use description array names<br /># use array index that unifies the arrays<br /><br /># first the counts for the number of files<br /><br />			u_count[user " *"]++;<br />			g_count["* " group]++;<br />			ug_count[user " " group]++;<br />			all_count["* *"]++;<br /><br /># then the total disk space used<br /><br />			u_size[user " *"]+=size;<br />			g_size["* " group]+=size;<br />			ug_size[user " " group]+=size;<br />			all_size["* *"]+=size;<br />		}<br />        }<br />}<br />END {<br /># output in a form that can be sorted<br />        for (i in u_count) {<br />				if (i != "") {<br />        	        print u_size[i], u_count[i], i;<br />				}<br />        }<br />        for (i in g_count) {<br />				if (i != "") {<br />        	        print g_size[i], g_count[i], i;<br />				}<br />        }<br />        for (i in ug_count) {<br />				if (i != "") {<br />        	        print ug_size[i], ug_count[i], i;<br />				}<br />        }<br />        for (i in all_count) {<br />				if (i != "") {<br />        	        print all_size[i], all_count[i], i;<br />				}<br />        }<br />} ' | <br /># numeric sort - biggest numbers first<br /># sort fields 0 and 1 first (sort starts with 0)<br /># followed by dictionary sort on fields 2 + 3<br />sort +0nr -2 +2d | <br /># add header<br />(echo "size count user group";cat -) |<br /># convert space to tab - makes it nice output<br /># the second set of quotes contains a single tab character<br />tr ' ' '	' <br /># done - I hope you like it<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/count_users3.awk">count_users3.awk</a><br /></p><p>Remember when I said I didn't need to use 4 different arrays? I can use just one. This is more confusing, but more concise </p><pre>#!/bin/sh<br />find . -type f -print | xargs /usr/bin/ls -islg | <br />awk '<br />BEGIN {<br /># initialize all arrays used in for loop<br />	count[""]=0;<br />}<br />{<br /># validate your input<br />        if (NF != 11) {<br />#	ignore<br />	} else {<br /># assign field names<br />		inode=$1;<br />		size=$2;<br />		linkcount=$4;<br />		user=$5;<br />		group=$6; <br /><br /># should I count this file?<br /><br />		doit=0;<br />		if (linkcount == 1) {<br /># only one copy - count it<br />			doit++;<br />		} else {<br /># a hard link - only count first one<br />			seen[inode]++;<br />			if (seen[inode] == 1) {<br />				doit++;<br />			}<br />		}<br /># if doit is true, then count the file<br />		if (doit ) {<br /><br /># total up counts in one pass<br /># use description array names<br /># use array index that unifies the arrays<br /><br /># first the counts for the number of files<br /><br />			count[user " *"]++;<br />			count["* " group]++;<br />			count[user " " group]++;<br />			count["* *"]++;<br /><br /># then the total disk space used<br /><br />			size[user " *"]+=size;<br />			size["* " group]+=size;<br />			size[user " " group]+=size;<br />			size["* *"]+=size;<br />		}<br />        }<br />}<br />END {<br /># output in a form that can be sorted<br />        for (i in count) {<br />		if (i != "") {<br />        	        print size[i], count[i], i;<br />		}<br />        }<br />} ' | <br /># numeric sort - biggest numbers first<br /># sort fields 0 and 1 first (sort starts with 0)<br /># followed by dictionary sort on fields 2 + 3<br />sort +0nr -2 +2d | <br /># add header<br />(echo "size count user group";cat -) |<br /># convert space to tab - makes it nice output<br /># the second set of quotes contains a single tab character<br />tr ' ' '	' <br /># done - I hope you like it<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/count_users.awk">count_users.awk</a><br /></p><h1><a name="uh-26" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-26">Picture Perfect PRINTF Output</a></h1><p> </p><p>So far, I described several simple scripts that provide useful information, in a somewhat ugly output format. Columns might not line up properly, and it is often hard to find patterns or trends without this unity. As you use AWK more, you will be desirous of crisp, clean formatting. To achieve this, you must master the <i>printf</i> function. </p><h1><a name="uh-27" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-27">PRINTF - formatting output</a></h1><p>The <i>printf</i> is very similar to the C function with the same name. C programmers should have no problem using <i>printf</i> function.  </p><p> <i>Printf</i> has one of these syntactical forms: </p><dl><dd>printf ( format);<br />printf ( format, arguments...);<br />printf ( format) >expression;<br />printf ( format, arguments...) > expression;<br /> </dd></dl><p>The parenthesis and semicolon are optional. I only use the first format to be consistent with other nearby  <i>printf</i> statements. A <i>print</i> statement would do the same thing. <i>Printf</i> reveals it's real power when formatting commands are used. </p><p>The first argument to the  <i>printf</i> function is the format.  This is a string, or variable whose value is a string. This string, like all strings, can contain special  escape sequences to print control characters. </p><h1><a name="uh-28" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-28">Escape Sequences</a></h1><p>The character "" is used to  "escape" or mark special characters. The list of these characters is in table  below: </p><pre>  +-------------------------------------------------------+<br />  |			AWK Table 5			  |<br />  |		      Escape Sequences			  |<br />  |Sequence   Description				  |<br />  +-------------------------------------------------------+<br />  |a	      ASCII bell (NAWK only)			  |<br />  |b	      Backspace					  |<br />  |f	      Formfeed					  |<br />  |n	      Newline					  |<br />  |r	      Carriage Return				  |<br />  |t	      Horizontal tab				  |<br />  |v	      Vertical tab (NAWK only)			  |<br />  |ddd	      Character (1 to 3 octal digits) (NAWK only) |<br />  |xdd	      Character (hexadecimal) (NAWK only)	  |<br />  |	      Any character c				  |<br />  +-------------------------------------------------------+</pre> <p> It's difficult to explain the differences without being wordy. Hopefully I'll provide enough examples  to demonstrate the differences. </p><p>With NAWK, you can print three tab characters using these three different representations: </p><dl><dd>printf("\t\11\x9\n");<br /> </dd></dl><p>A tab character is decimal 11, or hexadecimal 9. See the man page ascii(7) for more information. Similarly, you can print three double-quote characters  (decimal 42, hexadecimal 22) using </p><dl><dd>printf("\"\x22\42\n");<br /> </dd></dl><p> </p><p>You should notice a difference between the  <i>printf</i> function and the <i>print</i> function. <i>Print</i> terminates the line with the <b>OFS</b> character, and divides each field with the <b>ORS</b> separator. <i>Printf</i> does nothing unless you specify the action. Therefore you will frequently end each line with the newline character "n," and you must specify the separating characters explicitly. </p><p> </p><h1><a name="uh-29" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-29">Format Specifiers</a></h1><p>The power of the <i>printf</i> statement lies in the format specifiers, which always start with the character  "%." The format specifiers are described in table 6: </p><pre>	 +----------------------------------------+<br />	 |		AWK Table 6		  |<br />	 |	     Format Specifiers		  |<br />	 |Specifier   Meaning			  |<br />	 +----------------------------------------+<br />	 |c	      ASCII Character		  |<br />	 |d	      Decimal integer		  |<br />	 |e	      Floating Point number	  |<br />	 |	      (engineering format)	  |<br />	 |f	      Floating Point number	  |<br />	 |	      (fixed point format)	  |<br />	 |g	      The shorter of e or f,	  |<br />	 |	      with trailing zeros removed |<br />	 |o	      Octal			  |<br />	 |s	      String			  |<br />	 |x	      Hexadecimal		  |<br />	 |%	      Literal %			  |<br />	 +----------------------------------------+</pre>   <p>Again, I'll cover the differences quickly. Table 3 illustrates the differences. The first line states "printf(%cn",100.0)"" prints a "d."  </p><p> </p><pre>	     +--------------------------------+<br />	     |		AWK Table 7	      |<br />	     | Example of format conversions  |<br />	     |Format   Value	 Results      |<br />	     +--------------------------------+<br />	     |%c       100.0	 d	      |<br />	     |%c       "100.0"	 1 (NAWK?)    |<br />	     |%c       42	 "	      |<br />	     |%d       100.0	 100	      |<br />	     |%e       100.0	 1.000000e+02 |<br />	     |%f       100.0	 100.000000   |<br />	     |%g       100.0	 100	      |<br />	     |%o       100.0	 144	      |<br />	     |%s       100.0	 100.0	      |<br />	     |%s       "13f"	 13f	      |<br />	     |%d       "13f"	 0 (AWK)      |<br />	     |%d       "13f"	 13 (NAWK)    |<br />	     |%x       100.0	 64	      |<br />	     +--------------------------------+</pre>  <p>This table reveals some differences between  AWK and NAWK. When a string with numbers and letters are coverted into an integer, AWK will return a zero, while NAWK will convert as much as possible. The second example, marked with  "NAWK?" will return "d" on some earlier versions of NAWK, while later versions will return "1."  </p><p>Using format specifiers, there is another way to print a  double quote with NAWK. This demonstrates Octal, Decimal and Hexadecimal conversion. As you can see, it isn't symmetrical. Decimal conversions are done differently. </p><dl><dd>printf("%s%s%s%cn", """, "x22", "42", 34);<br /> </dd></dl><p>Between the  "%" and the format character can be four optional pieces of information. It helps to visualize these fields as: </p><dl><dd>%<sign><zero><width>.<precision>format<br /> </dd></dl><p> </p><p>I'll discuss each one separately. </p><h1><a name="uh-30" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-30">Width - specifying minimum field size</a></h1><p> </p><p>If there is a number after the "%," this specifies the minimum number of characters to print. This is the  <i>width</i> field. Spaces are added so the number of printed characters equal this number.  Note that this is the minimum field size. If the field becomes to large, it will grow, so information will not be lost. Spaces are added to the left. </p><p>This format allows you to line up columns perfectly. Consider the following format: </p><dl><dd>printf("%st%dn", s, d);<br /> </dd></dl><p>If the string  "s" is longer than 8 characters, the columns won't line up. Instead, use </p><dl><dd>printf("%20s%dn", s, d);<br /> </dd></dl><p> </p><p>As long as the string is less than 20 characters, the number will start on the 21st column. If the string is too long, then the two fields will run together, making it hard to read. You may want to consider placing a single space between the fields, to make sure you will always have one space between the fields. This is very important if you want to  pipe the output to another program. </p><p>Adding informational headers makes the output more readable. Be aware that changing the format of the data may make it difficult to get the columns aligned perfectly. Consider the following script: <br /><br />#!/usr/bin/awk -f<br />BEGIN {<br />	printf("String     Numbern");<br />}<br />{<br />	printf("%10s %6dn", $1, $2);<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example9.awk">awk_example9.awk</a><br />It would be awkward (forgive the choice of words) to add a new column and retain the same alignment. More complicated formats would require a lot of trial and error. You have to adjust the first  <i>printf</i> to agree with the second  <i>printf</i> statement. I suggest <br /><br />#!/usr/bin/awk -f<br />BEGIN {<br />	printf("%10s %6sn", "String", "Number");<br />}<br />{<br />	printf("%10s %6dn", $1, $2);<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example10.awk">awk_example10.awk</a><br /></p><p>or even better <br /><br />#!/usr/bin/awk -f<br />BEGIN {<br />	format1 ="%10s %6sn";<br />	format2 ="%10s %6dn";<br />	printf(format1, "String", "Number");<br />}<br />{<br />	printf(format2, $1, $2);<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example11.awk">awk_example11.awk</a><br /></p><p>The last example, by using string variables for formatting, allows you to keep all of the formats together. </p><h1><a name="uh-31" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-31">Left Justification</a></h1><p>The last example places spaces before each field to make sure the minimum field width is met. What do you do if you want the spaces on the right? Add a negative sign before the width: </p><dl><dd>	printf("%-10s %-6dn", $1, $2);<br /> </dd></dl><p> </p><p>This will move the printing characters to the left, with spaces added to the right.  </p><h1><a name="uh-32" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-32">The Field Precision Value</a></h1><p> </p><p>The precision field, which is the number between the decimal and the format character, is more complex. Most people use it with the floating point format (%f), but surprisingly, it can be used with any format character. With the octal, decimal or hexadecimal format, it specifies the minimum number of characters. Zeros are added to met this requirement. With the %e and %f formats, it specifies the number of digits after the decimal point.  The %e  "e+00" is not included in the precision. The %g format combines the characteristics of the %d and %f formats. The precision specifies the number of digits displayed, before and after the decimal point. The precision field has no effect on the %c field. The %s format has an unusual, but useful effect: it specifies the maximum number of significant characters to print. </p><p>If the first number after the  "%," or after the "%-," is a zero, then the system adds zeros when padding. This includes all format types, including strings and the %c character format. This means  "%010d" and  "%.10d" both adds leading zeros, giving a minimum of 10 digits. The format "%10.10d" is therefore redundant. Table 8 gives some examples: </p><p> </p><pre>       +--------------------------------------------+<br />       |		AWK Table 8		    |<br />       |      Examples of complex formatting	    |<br />       |Format	  Variable	   Results	    |<br />       +--------------------------------------------+<br />       |%c	  100		   "d"		    |<br />       |%10c	  100		   "	     d"	    |<br />       |%010c	  100		   "000000000d"	    |<br />       +--------------------------------------------+<br />       |%d	  10		   "10"		    |<br />       |%10d	  10		   "	    10"	    |<br />       |%10.4d	  10.123456789	   "	  0010"	    |<br />       |%10.8d	  10.123456789	   "  00000010"	    |<br />       |%.8d	  10.123456789	   "00000010"	    |<br />       |%010d	  10.123456789	   "0000000010"	    |<br />       +--------------------------------------------+<br />       |%e	  987.1234567890   "9.871235e+02"   |<br />       |%10.4e	  987.1234567890   "9.8712e+02"	    |<br />       |%10.8e	  987.1234567890   "9.87123457e+02" |<br />       +--------------------------------------------+<br />       |%f	  987.1234567890   "987.123457"	    |<br />       |%10.4f	  987.1234567890   "  987.1235"	    |<br />       |%010.4f	  987.1234567890   "00987.1235"	    |<br />       |%10.8f	  987.1234567890   "987.12345679"   |<br />       +--------------------------------------------+<br />       |%g	  987.1234567890   "987.123"	    |<br />       |%10g	  987.1234567890   "   987.123"	    |<br />       |%10.4g	  987.1234567890   "	 987.1"	    |<br />       |%010.4g	  987.1234567890   "00000987.1"	    |<br />       |%.8g	  987.1234567890   "987.12346"	    |<br />       +--------------------------------------------+<br />       |%o	  987.1234567890   "1733"	    |<br />       |%10o	  987.1234567890   "	  1733"	    |<br />       |%010o	  987.1234567890   "0000001733"	    |<br />       |%.8o	  987.1234567890   "00001733"	    |<br />       +--------------------------------------------+<br />       |%s	  987.123	   "987.123"	    |<br />       |%10s	  987.123	   "   987.123"	    |<br />       |%10.4s	  987.123	   "	  987."	    |<br />       |%010.8s	  987.123	   "000987.123"	    |<br />       +--------------------------------------------+<br />       |%x	  987.1234567890   "3db"	    |<br />       |%10x	  987.1234567890   "	   3db"	    |<br />       |%010x	  987.1234567890   "00000003db"	    |<br />       |%.8x	  987.1234567890   "000003db"	    |<br />       +--------------------------------------------+</pre>  <p>There is one more topic needed to complete this lesson on <i>printf</i>.  </p><h1><a name="uh-33" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-33">Explicit File output</a></h1><p>Instead of sending output to standard output, you can send output to a named file. The format is </p><dl><dd>printf("stringn") > "/tmp/file";<br /> </dd></dl><p> </p><p>You can append to an existing file, by using ">>:"  </p><dl><dd>printf("stringn") >> "/tmp/file";<br /> </dd></dl><p>Like the shell, the double angle brackets indicates output is  <b>appended</b> to the file, instead of  <b>written</b> to an empty file. Appending to the file does not delete the old contents. However, there is a subtle difference between AWK and the shell. </p><p>Consider the shell program: </p><dl><dd>#!/bin/sh<br />while x=`line`<br />do<br />	echo got $x >>/tmp/a<br />	echo got $x >/tmp/b<br />done<br /> </dd></dl><p> </p><p>This will read standard input, and copy the standard input to files "/tmp/a" and  "/tmp/b." File  "/tmp/a" will grow larger, as information is always appended to the file. File  "/tmp/b," however, will only contain one line. This happens because each time the shell see the ">" or ">>" characters, it opens the file for writing, choosing the truncate/create or appending option at that time. </p><p>Now consider the equivalent AWK program: </p><dl><dd>#!/usr/bin/awk -f<br />{<br />    print $0 >>"/tmp/a"<br />    print $0 >"/tmp/b"<br />}<br /> </dd></dl><p> </p><p>This behaves differently. AWK chooses the create/append option the first time a file is opened for writing. Afterwards, the use of  ">" or ">>" is ignored. Unlike the shell, AWK copies all of standard input to file "/tmp/b."  </p><p>Instead of a string, some versions of AWK allow you to specify an expression: </p><dl><dd># [note to self] check this one - it might not work<br />printf("stringn") > FILENAME ".out";<br /> </dd></dl><p>The following uses a string concatenation expression to illustrate this: <br /><br />#!/usr/bin/awk -f<br />END {<br />    for (i=0;i<30;i++) {<br />	printf("i=%dn", i) > "/tmp/a" i;<br />    }<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example12.awk">awk_example12.awk</a><br />This script never finishes, because  AWK can have 10 additional files open, and NAWK can have 20. If you find this to be a problem, look into PERL. </p><p>I hope this gives you the skill to make your AWK output picture perfect. </p><h1><a name="uh-34" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-34">AWK Numerical Functions</a></h1><p>In previous tutorials, I have shown how useful AWK is in manipulating  information, and generating reports. When you add a few functions, AWK becomes even more, mmm, functional. </p><p>There are three types of functions: numeric, string and whatever's left. Table9 lists all of the numeric functions: </p><pre>	    +----------------------------------+<br />	    |		AWK Table 9	       |<br />	    +----------------------------------+<br />	    |	     Numeric Functions	       |<br />	    |Name    Function	   Variant     |<br />	    +----------------------------------+<br />	    |cos     cosine	   AWK	       |<br />	    |exp     Exponent	   AWK	       |<br />	    |int     Integer	   AWK	       |<br />	    |log     Logarithm	   AWK	       |<br />	    |sin     Sine	   AWK	       |<br />	    |sqrt    Square Root   AWK	       |<br />	    |atan2   Arctangent	   NAWK	       |<br />	    |rand    Random	   NAWK	       |<br />	    |srand   Seed Random   NAWK	       |<br />	    +----------------------------------+</pre>  <h1><a name="uh-35" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-35">Trigonometric Functions</a></h1><p>Oh joy. I bet millions, if not dozens, of my readers have been waiting for me to discuss trigonometry. Personally, I don't use trigonometry much at work, except when I go off on a tangent. </p><p>Sorry about that. I don't know what came over me. I don't usually resort to puns. I'll write a note to myself, and after I sine the note, I'll have  my boss cosine it. </p><p><b>Now stop that!</b> I hate arguing with myself. I always lose. Thinking about math I learned in the year 2 B.C. (Before Computers) seems to cause flashbacks of high school, pimples, and (shudder) times best left forgotten. The stress of remembering those days must have made me forget the standards I normally set for myself. Besides, no-one appreciates obtuse humor anyway, even if I find acute  way to say it. </p><p>I better change the subject fast.  Combining humor and computers is a very serious matter.  </p><p>Here is a NAWK script that calculates the trigonometric functions for all degrees between 0 and 360. It also shows why there is no tangent, secant or cosecant function. (They aren't necessary). If you read the  script, you will learn of some subtle differences between AWK and NAWK. All this in a thin veneer of demonstrating why we learned trigonometry in the first place. What more can you ask for? Oh, in case you are wondering, I wrote this in the month of December. </p><pre>#!/usr/bin/nawk -f<br />#<br /># A smattering of trigonometry...<br />#<br /># This AWK script plots the values from 0 to 360<br /># for the basic trigonometry functions<br /># but first - a review:<br />#<br /># (Note to the editor - the following diagram assumes<br /># a fixed width font, like Courier. <br /># otherwise, the diagram  looks very stupid, instead of slightly stupid)<br />#<br /># Assume the following right triangle<br />#<br />#       Angle Y<br />#<br />#       |<br />#       | <br />#       |  <br />#     a |     c<br />#       |    <br />#       |     <br />#       +-------   Angle X<br />#          b<br />#<br /># since the triangle is a right angle, then<br />#	X+Y=90<br />#<br /># Basic Trigonometric Functions. If you know the length<br /># of 2 sides, and the angles, you can find the length of the third side.<br /># Also - if you know the length of the sides, you can calculate <br /># the angles.<br />#<br /># The formulas are<br />#<br />#	sine(X) = a/c<br />#	cosine(X) = b/c<br />#	tangent(X) = a/b<br />#<br /># reciprocal functions<br />#	cotangent(X) = b/a<br />#	secant(X) = c/b<br />#	cosecant(X) = c/a<br />#<br /># Example 1)<br /># if an angle is 30, and the hypotenuse (c) is 10, then<br /># 	a = sine(30) * 10 = 5<br />#	b = cosine(30) * 10 =  8.66<br />#<br /># The second example will be more realistic:<br />#<br /># 	Suppose you are looking for a Christmas tree, and<br /># while talking to your family, you smack into a tree<br /># because your head was turned, and your kids were arguing over who<br /># was going to put the first ornament on the tree.<br />#<br /># As you come to, you realize your feet are touching the trunk of the tree,<br /># and your eyes are 6 feet from the bottom of your frostbitten toes.<br /># While counting the stars that spin around your head, you also realize<br /># the top of the tree is located at a 65 degree angle, relative to your eyes.<br /><br /># You suddenly realize the tree is 12.84 feet high! After all, <br /># 	tangent(65 degrees) * 6 feet = 12.84 feet<br /><br /># All right, it isn't realistic. Not many people memorize the<br /># tangent table, or can estimate angles that accurately. <br /># I was telling the truth about the stars spinning around the head, however. <br /><br />#<br />BEGIN {<br /># assign a value for pi.<br />	PI=3.14159;<br /># select an "Ed Sullivan" number - really really big<br />	BIG=999999;	<br /># pick two formats<br /># Keep them close together, so when one column is made larger<br /># the other column can be adjusted to be the same width<br />	fmt1="%7s %8s %8s %8s %10s %10s %10s %10sn";<br /># print out the title of each column<br />	fmt2="%7d %8.2f %8.2f %8.2f %10.2f %10.2f %10.2f %10.2fn";<br /># old AWK wants a backslash at the end of the next line<br /># to continue the print statement<br /># new AWK allows you to break the line into two, after a comma<br />	printf(fmt1,"Degrees","Radians","Cosine","Sine", <br />		"Tangent","Cotangent","Secant", "Cosecant");<br /><br />	for (i=0;i<=360;i++) {<br /># convert degrees to radians<br />		r = i * (PI / 180 );<br /># in new AWK, the backslashes are optional<br /># in OLD AWK, they are required<br />		printf(fmt2, i, r, <br /># cosine of r<br />		cos(r), <br /># sine of r<br />		sin(r), <br />#<br /># I ran into a problem when dividing by zero.<br /># So I had to test for this case.<br />#<br /># old AWK finds the next line too complicated<br /># I don't mind adding a backslash, but rewriting the<br /># next three lines seems pointless for a simple lesson.<br /># This script will only work with new AWK, now - sigh...<br /># On the plus side, <br />#   I don't need to add those back slashes anymore<br />#<br /># tangent of r<br />		(cos(r) == 0) ? BIG : sin(r)/cos(r), <br /># cotangent of r<br />		(sin(r) == 0) ? BIG : cos(r)/sin(r), <br /># secant of r<br />		(cos(r) == 0) ? BIG : 1/cos(r), <br /># cosecant of r<br />		(sin(r) == 0) ? BIG : 1/sin(r));<br />	}<br /># put an exit here, so that standard input isn't needed.<br />	exit;<br />}<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/trigonometry.awk">trigonometry.awk</a><br /></p><p>NAWK also has the arctangent function. This is useful for some graphics work, as </p><dl><dd>arc tangent(a/b) = angle (in radians)<br /> </dd></dl><p>Therefore if you have the X and Y locations, the arctangent of the ratio will tell you the angle. The  <i>atan2</i>() function returns a value from negative  <i>pi</i> to positive  <i>pi</i>.  </p><h1><a name="uh-36" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-36">Exponents, logs and square roots</a></h1><p>The following script uses three other arithmetic functions:  <i>log</i>,  <i>exp</i>, and <i>sqrt</i>. I wanted to show how these can be used together, so I divided the log of a number by two, which is another way to find a square root. I then compared the value of the exponent of that new log to the built-in square root function. I then calculated the difference between the two, and converted the difference into a positive number. </p><pre>#!/bin/awk -f<br /># demonstrate use of exp(), log() and sqrt in AWK<br /># e.g. what is the difference between using logarithms and regular arithmetic<br /># note - exp and log are natural log functions - not base 10<br />#<br />BEGIN {<br /># what is the about of error that will be reported?<br />	ERROR=0.000000000001;<br /># loop a long while<br />	for (i=1;i<=2147483647;i++) {<br /># find log of i<br />		logi=log(i);<br /># what is square root of i? <br /># divide the log by 2<br />		logsquareroot=logi/2;<br /># convert log of i back<br />		squareroot=exp(logsquareroot);<br /># find the difference between the logarithmic calculation<br /># and the built in calculation<br />		diff=sqrt(i)-squareroot;<br /># make difference positive <br />		if (diff < 0) {<br />			diff*=-1;<br />		}<br />		if (diff > ERROR) {<br />			printf("%10d, squareroot: %16.8f, error: %16.14fn", <br />				i, squareroot, diff);<br />		}<br />	}<br />	exit;<br />}<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example13.awk">awk_example13.awk</a><br />Yawn. This example isn't too exciting, except to those who enjoy nitpicking. Expect the program to reach 3 million before you see any errors. I'll give you a more exciting sample soon. </p><h1><a name="uh-37" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-37">Truncating Integers</a></h1><p>All version of AWK contain the <i>int</i> function. This truncates a number, making it an integer. It can be used to round numbers by adding 0.5: </p><dl><dd>printf("rounding %8.4f gives %8dn", x, int(x+0.5));<br /> </dd></dl><p> </p><h1><a name="uh-38" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-38">"Random Numbers</a></h1><p>NAWK has functions that can generate random numbers. The function <i>rand</i> returns a random number between 0 and 1. Here is an example that calculates a million random numbers between 0 and 100, and counts how often each number was used: </p><pre>#!/usr/bin/nawk -f<br /># old AWK doesn't have rand() and srand()<br /># only new AWK has them<br /># how random is the random function?<br />BEGIN {<br />#	srand();<br />	i=0;<br />	while (i++<1000000) {<br />		x=int(rand()*100 + 0.5);<br />		y[x]++;<br />	}<br />	for (i=0;i<=100;i++) {<br />		printf("%dt%dn",y[i],i);<br />	}<br />	exit;<br />}<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/random.awk">random.awk</a><br /></p><p>If you execute this script several times, you will get the exact same results. Experienced programmers know random number generators aren't really random, unless they use special hardware. These numbers are pseudo-random, and calculated using some algorithm. Since the algorithm is fixed, the numbers are repeatable unless the numbers are seeded with a unique value. This is done using the <i>srand</i> function above, which is commented out. Typically the random number generator is not given a special seed until the bugs have been worked out of the program. There's nothing more frustrating than a bug that occurs randomly. The <i>srand</i> function may be given an argument. If not, it uses the current time and day to generate a seed for the random number generator. </p><h1><a name="uh-39" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-39">The Lotto script</a></h1><p>I promised a more useful script. This may be what you are waiting for. It reads two numbers, and generates a list of random numbers. I call the script "lotto.awk."  </p><pre>#!/usr/bin/nawk -f<br />BEGIN {<br /># Assume we want 6 random numbers between 1 and 36<br /># We could get this information by reading standard input,<br /># but this example will use a fixed set of parameters.<br />#<br /># First, initialize the seed<br />    srand();<br /># How many numbers are needed?<br />    NUM=6;<br /># what is the minimum number<br />    MIN=1;<br /># and the maximum?<br />    MAX=36;<br /># How many numbers will we find? start with 0<br />    Number=0;<br />    while (Number < NUM) {<br />	r=int(((rand() *(1+MAX-MIN))+MIN));<br /># have I seen this number before?<br />	if (array[r] == 0) {<br /># no, I have not<br />	    Number++;<br />	    array[r]++;<br />	}<br />    }<br /><br /># now output all numbers, in order<br />    for (i=MIN;i<=MAX;i++) {<br /># is it marked in the array?<br />	if (array[i]) {<br /># yes<br />	    printf("%d ",i);<br />	}<br />    }<br />    printf("n");<br />    exit;<br />}<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/lotto.awk">lotto.awk</a><br />If you do win a lottery, send me a postcard. </p><p> </p><h1><a name="uh-40" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-40">String Functions</a></h1><p> </p><p>Besides numeric functions, there are two other types of function: strings and the whatchamacallits. First, a list of the string functions: </p><pre>     +-------------------------------------------------+<br />     |			AWK Table 10		       |<br />     |		      String Functions		       |<br />     |Name			       Variant	       |<br />     +-------------------------------------------------+<br />     |index(string,search)	       AWK, NAWK, GAWK |<br />     |length(string)		       AWK, NAWK, GAWK |<br />     |split(string,array,separator)    AWK, NAWK, GAWK |<br />     |substr(string,position)	       AWK, NAWK, GAWK |<br />     |substr(string,position,max)      AWK, NAWK, GAWK |<br />     |sub(regex,replacement)	       NAWK, GAWK      |<br />     |sub(regex,replacement,string)    NAWK, GAWK      |<br />     |gsub(regex,replacement)	       NAWK, GAWK      |<br />     |gsub(regex,replacement,string)   NAWK, GAWK      |<br />     |match(string,regex)	       NAWK, GAWK      |<br />     |tolower(string)		       GAWK	       |<br />     |toupper(string)		       GAWK	       |<br />     +-------------------------------------------------+</pre>  <p>Most people first use AWK to perform simple calculations. Associative arrays and trigonometric functions are somewhat esoteric features, that new users embrace with the eagerness of a chain smoker in a fireworks factory. I suspect most users add some simple string functions to their repertoire once they want to add a little more sophistication to their AWK scripts. I hope this column gives you enough information to inspire your next effort. </p><p>There are four string functions in the original AWK: <i>index</i>(),  <i>length</i>(),  <i>split</i>(), and <i>substr</i>(). These functions are quite versatile. </p><h1><a name="uh-41" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-41">The Length function</a></h1><p>What can I say? The  <i>length</i>() function calculates the length of a string. I often use it to make sure my input is correct. If you wanted to ignore empty lines, check the length of the each line before processing it with  </p><dl><dd>if (length($0) > 1) {<br /> . . .<br />}<br /> </dd></dl><p>You can easily use it to print all lines longer than a certain length, etc. The following command centers all lines shorter than 80 characters: <br /><br />#!/bin/awk -f<br />{<br />    if (length($0) < 80) {<br />        prefix = "";<br />        for (i = 1;i<(80-length($0))/2;i++)<br />            prefix = prefix " ";<br />        print prefix $0;<br />    } else {<br />        print;<br />    }<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/center.awk">center.awk</a><br /></p><h1><a name="uh-42" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-42">The Index Function</a></h1><p> </p><p>If you want to search for a special character, the <i>index</i>() function will search for specific characters inside a string. To find a comma, the code might look like this: </p><dl><dd>sentence="This is a short, meaningless sentence.";<br />if (index(sentence, ",") > 0) {<br />    printf("Found a comma in position %dn", index(sentence,","));<br />}<br /> </dd></dl><p>The function returns a positive value when the substring is found. The number specified the location of the substring. </p><p>If the substring consists of 2 or more characters, all of these characters must be found, in the same order, for a non-zero return value. Like the  <i>length</i>() function, this is useful for checking for proper input conditions. </p><h1><a name="uh-43" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-43">The Substr function</a></h1><p>The  <i>substr</i>() function can extract a portion of a string. One common use is to split a string into two parts based on a special character. If you wanted to process some mail addresses, the following code fragment might do the job: <br /><br />#!/bin/awk -f<br />{<br /># field 1 is the e-mail address - perhaps<br />    if ((x=index($1,"@")) > 0) {<br />        username = substr($1,1,x-1);<br />        hostname = substr($1,x+1,length($1));<br /># the above is the same as<br />#        hostname = substr($1,x+1);<br />        printf("username = %s, hostname = %sn", username, hostname);<br />    }<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/email.awk">email.awk</a><br />The <i>substr</i>() function takes two or three arguments. The first is the string, the second is the position. The optional third argument is the length of the string to extract. If the third argument is missing, the rest of the string is used. </p><p>The substr function can be used in many non-obvious ways. As an example, it can be used to convert upper case letters to lower case. </p><pre>#!/usr/bin/awk -f<br /># convert upper case letters to lower case<br />BEGIN {<br />    LC="abcdefghijklmnopqrstuvwxyz";<br />    UC="ABCDEFGHIJKLMNOPQRSTUVWXYZ";<br />}<br />{<br />    out="";<br /># look at each character<br />    for(i=1;i<=length($0);i++) {<br /># get the character to be checked<br />        char=substr($0,i,1);<br /># is it an upper case letter?<br />        j=index(UC,char);<br />            if (j > 0 ) {<br /># found it<br />                out = out substr(LC,j,1);<br />            } else {<br />                out = out char;<br />            }<br />    }<br />    printf("%sn", out);<br />}    <br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/upper_to_lower.awk">upper_to_lower.awk</a><br /></p><h1><a name="uh-44" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-44">GAWK's Tolower and Toupper function</a></h1><p> </p><p>GAWK has the <i>toupper</i>() and <i>tolower</i>() functions, for convenient conversions of case. These functions take strings, so you can reduce the above script to a single line: <br /><br />#!/usr/local/bin/gawk -f<br />{<br />    print tolower($0);<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/upper_to_lower.gawk">upper_to_lower.gawk</a><br /></p><h1><a name="uh-45" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-45">The Split function</a></h1><p>Another way to split up a string is to use the <i>split</i>() function. It takes three arguments: the string, an array, and the separator. The function returns the number of pieces found. Here is an example: <br /><br />#!/usr/bin/awk -f<br />BEGIN {<br /># this script breaks up the sentence into words, using <br /># a space as the character separating the words<br />    string="This is a string, is it not?";<br />    search=" ";<br />    n=split(string,array,search);<br />    for (i=1;i<=n;i++) {<br />        printf("Word[%d]=%sn",i,array[i]);<br />    }<br />    exit;<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example14.sh">awk_example14.sh</a><br /></p><p>The third argument is typically a single character. If a longer string is used, only the first letter is used as a separator. </p><h1><a name="uh-46" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-46">NAWK's string functions</a></h1><p>NAWK (and GAWK) have additional string functions, which add  a primitive SED-like functionality: <i>sub</i>(),  <i>match</i>(), and <i>gsub</i>().  </p><p> <i>Sub</i>() performs a string substitution, like  <i>sed</i>. To replace "old" with "new" in a string, use </p><dl><dd>sub(/old/, "new", string)<br /> </dd></dl><p>If the third argument is missing, $0 is assumed to be string searched. The function returns 1 if a substitution occurs, and 0 if not. If no slashes are given in the first argument, the first argument is assumed to be a variable containing a regular expression. The <i>sub</i>() only changes the first occurrence. The <i>gsub</i>() function is similar to the  <b>g</b> option in  <i>sed</i>: all occurrence are converted, and not just the first. That is, if the patter occurs more than once per line (or string), the substitution will be performed once for each found pattern. The following script: <br /><br />#!/usr/bin/nawk -f<br />BEGIN {<br />    string = "Another sample of an example sentence";<br />    pattern="[Aa]n";<br />    if (gsub(pattern,"AN",string)) {<br />        printf("Substitution occurred: %sn", string);<br />    }<br /><br />    exit;<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example15.awk">awk_example15.awk</a><br /></p><p>print the following when executed: </p><dl><dd>Substitution occurred: ANother sample of AN example sentence<br /> </dd></dl><p> </p><p>As you can see, the pattern can be a regular expression. </p><h1><a name="uh-47" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-47">The Match function</a></h1><p>As the above demonstrates, the <i>sub</i>() and  <i>gsub</i>() returns a positive value if a match is found. However, it has a side-effect of changing the string tested. If you don't wish this, you can copy the string to another variable, and test the spare variable. NAWK also provides the  <i>match</i>() function. If  <i>match</i>() finds the regular expression, it sets two special variables that indicate where the regular expression begins and ends. Here is an example that does this: <br /><br />#!/usr/bin/nawk -f<br /># demonstrate the match function<br /><br />BEGIN {<br />    regex="[a-zA-Z0-9]+";<br />}<br />{<br />    if (match($0,regex)) {<br />#           RSTART is where the pattern starts<br />#           RLENGTH is the length of the pattern<br />            before = substr($0,1,RSTART-1);<br />            pattern = substr($0,RSTART,RLENGTH);<br />            after = substr($0,RSTART+RLENGTH);<br />            printf("%s<%s>%sn", before, pattern, after);<br />    }<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example16.awk">awk_example16.awk</a><br /></p><p>Lastly, there are the whatchamacallit functions. I could use the word "miscellaneous," but it's too hard to spell. Darn it, I had to look it up anyway.  </p><pre>      +-----------------------------------------------+<br />      |			AWK Table 11		      |<br />      |		  Miscellaneous Functions	      |<br />      |Name			      Variant	      |<br />      +-----------------------------------------------+<br />      |getline			      AWK, NAWK, GAWK |<br />      |getline <file		      NAWK, GAWK      |<br />      |getline variable		      NAWK, GAWK      |<br />      |getline variable <file      NAWK, GAWK         |<br />      |"command" | getline	      NAWK, GAWK      |<br />      |"command" | getline variable   NAWK, GAWK      |<br />      |system(command)		      NAWK, GAWK      |<br />      |close(command)		      NAWK, GAWK      |<br />      |systime()		      GAWK	      |<br />      |strftime(string)		      GAWK	      |<br />      |strftime(string, timestamp)    GAWK	      |<br />      +-----------------------------------------------+</pre> <p>  </p><h1><a name="uh-48" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-48">The System function</a></h1><p>NAWK has a function  <i>system</i>() that can execute any program. It returns the exit status of the program. </p><dl><dd>if (system("/bin/rm junk") != 0)<br />    print "command didn't work";<br /> </dd></dl><p>The command can be a string, so you can dynamically create commands based on input. Note that the output isn't sent to the NAWK program. You could send it to a file, and open that file for reading. There is another solution, however. </p><h1><a name="uh-49" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-49">The Getline function</a></h1><p>AWK has a command that allows you to force a new line. It doesn't take any arguments. It returns a 1, if successful, a 0 if end-of-file is reached, and a -1 if an error occurs. As a side effect, the line containing the input changes. This next script filters the input, and if a backslash occurs at the end of the line, it reads the next line in, eliminating the backslash as well as the need for it. <br /><br />#!/usr/bin/awk -f<br /># look for a  as the last character.<br /># if found, read the next line and append<br />{<br />    line = $0;<br />    while (substr(line,length(line),1) == "") {<br /># chop off the last character<br />        line = substr(line,1,length(line)-1);<br />        i=getline;<br />        if (i > 0) {<br />            line = line $0;<br />        } else {<br />            printf("missing continuation on line %dn", NR);<br />        }<br />    }<br />    print line;<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example17.awk">awk_example17.awk</a><br /></p><p>Instead of reading into the standard variables, you can specify the variable to set: </p><dl><dd>getline a_line<br />print a_line;<br /> </dd></dl><p>NAWK  and GAWK allow the <i>getline</i> function to be given an optional filename or string containing a filename. An example of a primitive file preprocessor, that looks for lines of the format </p><dl><dd>#include filename<br /> </dd></dl><p>and substitutes that line for the contents of the file: <br /><br />#!/usr/bin/nawk -f<br />{<br /># a primitive include preprocessor<br />    if (($1 == "#include") && (NF == 2)) {<br /># found the name of the file<br />        filename = $2;<br />        while (i = getline < filename ) {<br />            print;<br />        }<br />    } else {<br />        print;<br />    }<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/include.nawk">include.nawk</a><br /></p><p>NAWK's getline can also read from a pipe. If you have a program that generates  single line, you can use </p><dl><dd>"command" | getline;<br />print $0;<br /> </dd></dl><p> </p><p>or </p><dl><dd>"command" | getline abc;<br />print abc;<br /> </dd></dl><p> </p><p>If you have more than one line, you can loop through the results: </p><dl><dd>while ("command" | getline) {<br />    cmd[i++] = $0;<br />}<br /><p><br />for (i in cmd) {<br />    printf("%s=%sn", i, cmd[i]);<br />}<br /> </p></dd></dl><p> </p><p>Only one pipe can be open at a time. If you want to open another pipe, you must execute </p><dl><dd>close("command");<br /> </dd></dl><p> </p><p>This is necessary even if the end of file is reached. </p><h1><a name="uh-50" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-50">The systime function</a></h1><p>The <i>systime</i>() function returns the current time of day as the number of seconds since Midnight, January 1, 1970. It is useful for measuring how long portions of your GAWK code takes to execute. <br /><br /></p><pre>#!/usr/local/bin/gawk -f<br /># how long does it take to do a few loops?<br />BEGIN {<br />    LOOPS=100;<br /># do the test twice<br />    start=systime();<br />    for (i=0;i<LOOPS;i++) {<br />    }<br />    end = systime();<br /># calculate how long it takes to do a dummy test<br />    do_nothing = end-start;<br /># now do the test again with the *IMPORTANT* code inside<br />    start=systime();<br />    for (i=0;i<LOOPS;i++) {<br /># How long does this take?<br />        while ("date" | getline) {<br />            date = $0;<br />        }<br />        close("date");<br />    }<br />    end = systime();<br />    newtime = (end - start) - do_nothing;<br /><br />    if (newtime <= 0) {<br />        printf("%d loops were not enough to test, increase itn", <br />            LOOPS);<br />        exit;<br />    } else {<br />        printf("%d loops took %6.4f seconds to executen", <br />            LOOPS, newtime);<br />        printf("That's %10.8f seconds per loopn", <br />            (newtime)/LOOPS);<br /># since the clock has an accuracy of +/- one second, what is the error<br />        printf("accuracy of this measurement = %6.2f%%n",<br />            (1/(newtime))*100);<br />    }<br />    exit;<br />}<br /><br /></pre> <p> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example17.gawk">awk_example17.gawk</a><br /></p><h1><a name="uh-51" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-51">The Strftime function</a></h1><p>GAWK has a special function for creating strings based on the current time. It's based on the <i>strftime</i>(3c) function. If you are familiar with the  "+" formats of the  <i>date</i>(1) command, you have a good head-start on understanding what the <i>strftime</i> command is used for. The <i>systime</i>() function returns the current date in seconds. Not very useful if you want to create a string based on the time. While you could convert the seconds into days, months, years, etc., it would be easier to execute "date" and pipe the results into a string. (See the previous script for an example). GAWK has another solution that eliminates the need for  an external program. </p><p>The function takes one or two arguments. The first argument is a string that specified the format. This string contains regular characters and special characters. Special characters start with a backslash or the percent character. The backslash characters with the backslash prefix are the same I covered earlier. In addition, the <i>strftime</i>() function defines dozens of combinations, all of which start with "%." The following table lists these special sequences: </p><pre>+---------------------------------------------------------------+<br />|			  AWK Table 12				|<br />|		    GAWK's strftime formats			|<br />+---------------------------------------------------------------+<br />|%a   The locale's abbreviated weekday name			|<br />|%A   The locale's full weekday name				|<br />|%b   The locale's abbreviated month name			|<br />|%B   The locale's full month name				|<br />|%c   The locale's "appropriate" date and time representation	|<br />|%d   The day of the month as a decimal number (01--31)		|<br />|%H   The hour (24-hour clock) as a decimal number (00--23)	|<br />|%I   The hour (12-hour clock) as a decimal number (01--12)	|<br />|%j   The day of the year as a decimal number (001--366)	|<br />|%m   The month as a decimal number (01--12)			|<br />|%M   The minute as a decimal number (00--59)			|<br />|%p   The locale's equivalent of the AM/PM			|<br />|%S   The second as a decimal number (00--61).			|<br />|%U   The week number of the year (Sunday is first day of week) |<br />|%w   The weekday as a decimal number (0--6).  Sunday is day 0	|<br />|%W   The week number of the year (Monday is first day of week) |<br />|%x   The locale's "appropriate" date representation		|<br />|%X   The locale's "appropriate" time representation		|<br />|%y   The year without century as a decimal number (00--99)	|<br />|%Y   The year with century as a decimal number			|<br />|%Z   The time zone name or abbreviation			|<br />|%%   A literal %.						|<br />+---------------------------------------------------------------+</pre>  <p>Depending on your operating system, and installation, you may also have the following formats: </p><pre>+-----------------------------------------------------------------------+<br />|			      AWK Table 13				|<br />|		     Optional GAWK strftime formats			|<br />+-----------------------------------------------------------------------+<br />|%D   Equivalent to specifying %m/%d/%y					|<br />|%e   The day of the month, padded with a blank if it is only one digit |<br />|%h   Equivalent to %b, above						|<br />|%n   A newline character (ASCII LF)					|<br />|%r   Equivalent to specifying %I:%M:%S %p				|<br />|%R   Equivalent to specifying %H:%M					|<br />|%T   Equivalent to specifying %H:%M:%S					|<br />|%t   A TAB character							|<br />|%k   The hour as a decimal number (0-23)				|<br />|%l   The hour (12-hour clock) as a decimal number (1-12)		|<br />|%C   The century, as a number between 00 and 99			|<br />|%u   is replaced by the weekday as a decimal number [Monday == 1]	|<br />|%V   is replaced by the week number of the year (using ISO 8601)	|<br />|%v   The date in VMS format (e.g. 20-JUN-1991)				|<br />+-----------------------------------------------------------------------+</pre>  <p>One useful format is </p><dl><dd>strftime("%y_%m_%d_%H_%M_%S")<br /> </dd></dl><p> </p><p>This constructs a string that contains the year, month, day, hour, minute and second in a format that allows convenient sorting. If you ran this at noon on Christmas, 1994, it would generate the string </p><dl><dd>94_12_25_12_00_00<br /> </dd></dl><p> </p><p> </p><p>Here is the GAWK equivalent of the date command: <br /><br />#! /usr/local/bin/gawk -f<br />#<br /><br />BEGIN {<br />    format = "%a %b %e %H:%M:%S %Z %Y";<br />    print strftime(format);<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/date.gawk">date.gawk</a><br /></p><p>You will note that there is no exit command in the begin statement. If I was using AWK, an exit statement is necessary. Otherwise, it would never terminate. If there is no action defined for each line read, NAWK and GAWK do not need an exit statement. </p><p>If you provide a second argument to the  <i>strftime</i>() function, it uses that argument as the timestamp, instead of the current system's time. This is useful for calculating future times. The following script calculates the time one week after the current time: <br /><br />#!/usr/local/bin/gawk -f<br />BEGIN {<br />#  get current time	<br />   ts = systime();<br /># the time is in seconds, so<br />   one_day = 24 * 60 * 60;<br />   next_week = ts + (7 * one_day);<br />   format = "%a %b %e %H:%M:%S %Z %Y";<br />   print strftime(format, next_week);<br />   exit;<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/one_week_later.gawk">one_week_later.gawk</a><br /></p><h1><a name="uh-52" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-52">User Defined Functions</a></h1><p>Finally, NAWK and GAWK support user defined functions. This function demonstrates a way to print error messages, including the filename and line number, if appropriate: <br /><br />#!/usr/bin/nawk -f<br />{<br />    if (NF != 4) {<br />        error("Expected 4 fields");<br />    } else {<br />        print;<br />    }<br />}<br />function error ( message ) {<br />    if (FILENAME != "-") {<br />        printf("%s: ", FILENAME) > "/dev/tty";<br />    }<br />    printf("line # %d, %s, line: %sn", NR, message, $0) >> "/dev/tty";<br />}<br /> <br />Click here to get file: <a href="http://www.grymoire.com/Unix/Scripts/awk_example18.nawk">awk_example18.nawk</a><br /></p><p> </p><h1><a name="uh-53" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-53">AWK patterns</a></h1><p> </p><p>In my first tutorial on AWK, I described the AWK statement as having the form </p><dl><dd>pattern {commands}<br /> </dd></dl><p> </p><p>I have only used two patterns so far: the special words <i>BEGIN</i> and <i>END</i>. Other patterns are possible, yet I haven't used any. There are several reasons for this. The first is that these patterns aren't necessary. You can duplicate them using an <i>if</i> statement. Therefore this is an  "advanced feature." Patterns, or perhaps the better word is conditions, tend to make an AWK program obscure to a beginner. You can think of them as an  advanced topic, one that should be attempted after becoming familiar with  the basics. </p><p>A pattern or condition is simply an abbreviated test. If the condition is true, the action is performed. All relational tests can be used as a pattern. The "tail -10" command, which prints the first 10 lines and stops, can be duplicated with </p><dl><dd>{if (NR <= 10 ) {print}}<br /> </dd></dl><p>Changing the <i>if</i> statement to a condition shortens the code: </p><dl><dd>NR <= 10 {print}<br /> </dd></dl><p> </p><p> </p><p>Besides relational tests, you can also use containment tests, i. e.  do strings contain regular expressions? Printing all lines that contain the word "special" can be written as </p><dl><dd>{if ($0 ~ /special/) {print}}<br /> </dd></dl><p> </p><p>or more briefly </p><dl><dd>$0 ~ /special/ {print}<br /> </dd></dl><p> </p><p>This type of test is so common, the authors of AWK allow a third, shorter format: </p><dl><dd>/special/ {print}<br /> </dd></dl><p> </p><p>These tests can be combined with the AND (<i>&&</i>) and OR (<i>||</i>) commands, as well as the NOT (<i>!</i>) operator. Parenthesis can also be added if you are in doubt, or to make your intention clear.  </p><p>The following condition prints the line if it contains the word "whole" or columns 1 and 2 contain "part1" and  "part2" respectively. </p><dl><dd>($0 ~ /whole/) || (($1 ~ /part1/) && ($2 ~ /part2/)) {print}<br /> </dd></dl><p> </p><p>This can be shortened to </p><dl><dd>/whole/ || $1 ~ /part1/ && $2 ~ /part2/ {print}<br /> </dd></dl><p> </p><p> </p><p>There is one case where adding parenthesis hurts. The condition </p><dl><dd>/whole/ {print}<br /> </dd></dl><p> </p><p>works, but </p><dl><dd>(/whole/) {print}<br /> </dd></dl><p> </p><p>does not. If parenthesis are used, it is necessary to explicitly specify the test: </p><dl><dd>($0 ~ /whole) {print}<br /> </dd></dl><p> </p><p>A murky situation arises when a simple variable is used as a condition. Since the variable <i>NF</i> specifies the number of fields on a line, one might think the statement </p><dl><dd>NF {print}<br /> </dd></dl><p>would print all lines with one of more fields. This is an illegal command for AWK, because AWK does not accept variables as conditions. To prevent a syntax error, I had to change it to </p><dl><dd>NF != 0 {print}<br /> </dd></dl><p> </p><p>I expected NAWK to work, but on some SunOS systems it refused to print any lines at all. On newer Solaris systems it did behave properly. Again, changing it to the longer form worked for all variations. GAWK, like the newer version of NAWK, worked properly. After this experience, I decided to leave other, exotic variations alone. Clearly this is unexplored territory.  I could write a script that prints the first 20 lines, except if there  were exactly three fields, unless it was line 10, by using </p><dl><dd>NF == 3 ? NR == 10 : NR < 20 { print }<br /> </dd></dl><p> </p><p>But I won't. Obscurity, like puns, is often unappreciated. </p><p>There is one more common and useful pattern I have not yet described. It is the comma separated pattern. A common example has the form: </p><dl><dd>/start/,/stop/ {print}<br /> </dd></dl><p> </p><p>This form defines, in one line, the condition to turn the action on, and the condition to turn the action off. That is, when a line containing "start" is seen, it is printed. Every line afterwards is also printed, until a line containing "stop" is seen. This one is also printed, but the line after, and all following lines, are not printed. This triggering on and off can be repeated many times. The equivalent code, using the <i>if</i> command, is: </p><dl><dd>{<br />  if ($0 ~ /start/) {<br />    triggered=1;<br />  }<br />  if (triggered) {<br />     print;<br />     if ($0 ~ /stop/) {<br />	triggered=0;<br />     }<br />  }<br />}<br /> </dd></dl><p> </p><p>The conditions do not have to be regular expressions. Relational tests can also be used. The following prints all lines between 20 and 40: </p><dl><dd>(NR==20),(NR==40) {print}<br /> </dd></dl><p> </p><p>You can mix relational and containment tests. The following prints every line until a "stop" is seen: </p><dl><dd>(NR==1),/stop/ {print}<br /> </dd></dl><p> </p><p>There is one more area of confusion about patterns: each one is independent of the others. You can have several patterns in a script; none influence the other patterns. If the following script is executed: </p><dl><dd>NR==10 {print}<br />(NR==5),(NR==15) {print}<br />/xxx/ {print}<br />(NR==1),/NeVerMatchThiS/ {print}<br /> </dd></dl><p> </p><p>and the input file's line 10 contains "xxx," it would be printed 4 times, as each condition is true.  You can think of each condition as cumulative. The exception is the special <b>BEGIN</b> and  <b>END</b> conditions. In the original AWK, you can only have one of each. In NAWK and GAWK, you can have several BEGIN or END actions. </p><h1><a name="uh-54" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-54">Formatting AWK programs</a></h1><p>Many readers have questions my style of AWK programming. In particular, they ask me why I include code like this: </p><dl><dd># Print column 3<br />print $3;<br /> </dd></dl><p> </p><p>when I could use </p><dl><dd>print $3 # print column 3<br /> </dd></dl><p> </p><p>After all, they reason, the semicolon is unnecessary,  and comments do not have to start on the first column. This is true. Still I avoid this. Years ago, when I started writing AWK programs, I would find myself confused when the nesting of conditions were too deep. If I moved a complex  <i>if</i> statement inside another  <i>if</i> statement, my alignment of braces became incorrect. It can be very difficult to repair this condition, especially with large  scripts. Nowadays I use <i>emacs</i> to do the formatting for me, but 10 years ago I didn't have this option. My solution was to use the program <i>cb</i>, which is a "C beautifier." By including optional semicolons, and starting comments on the first column of the line, I could send my AWK script through this filter, and properly align all of the code. </p><h1><a name="uh-55" href="http://www.grymoire.com/Unix/Awk.html#toc-uh-55">Environment Variables</a></h1><p>I've described the 7 special  variables in AWK, and briefly mentioned some others NAWK and GAWK. The complete list follows: </p><pre>	     +--------------------------------+<br />	     |	       AWK Table 14	      |<br />	     |Variable	    AWK	  NAWK	 GAWK |<br />	     +--------------------------------+<br />	     |FS	    Yes	  Yes	 Yes  |<br />	     |NF	    Yes	  Yes	 Yes  |<br />	     |RS	    Yes	  Yes	 Yes  |<br />	     |NR	    Yes	  Yes	 Yes  |<br />	     |FILENAME	    Yes	  Yes	 Yes  |<br />	     |OFS	    Yes	  Yes	 Yes  |<br />	     |ORS	    Yes	  Yes	 Yes  |<br />	     +--------------------------------+<br />	     |ARGC		  Yes	 Yes  |<br />	     |ARGV		  Yes	 Yes  |<br />	     |ARGIND			 Yes  |<br />	     |FNR		  Yes	 Yes  |<br />	     |OFMT		  Yes	 Yes  |<br />	     |RSTART		  Yes	 Yes  |<br />	     |RLENGTH		  Yes	 Yes  |<br />	     |SUBSEP		  Yes	 Yes  |<br />	     |ENVIRON			 Yes  |<br />	     |IGNORECASE		 Yes  |<br />	     |CONVFMT			 Yes  |<br />	     |ERRNO			 Yes  |<br />	     |FIELDWIDTHS		 Yes  |<br />	     +--------------------------------+

Since I've already discussed many of these, I'll only cover those that I missed earlier.

ARGC - Number or arguments (NAWK/GAWK)

The variable ARGC specifies the number of arguments on the command line. It always has the value of one or more, as it counts its own program name as the first argument. If you specify an AWK filename using the "-f" option, it is not counted as an argument. If you include a variable on the command line using the form below, NAWK does not count as an argument.

nawk -f file.awk x=17

GAWK does, but that is because GAWK requires the "-v" option before each assignment:

gawk -f file.awk -v x=17

GAWK variables initialized this way do not affect the ARGC variable.

ARGV - Array of arguments (NAWK/GAWK)

The ARGV array is the list of arguments (or files) passed as command line arguments.

ARGIND - Argument Index (GAWK only)

The ARGIND specifies the current index into the ARGV array, and therefore ARGV[ARGIND] is always the current filename. Therefore

FILENAME == ARGV[ARGIND]

is always true. It can be modified, allowing you to skip over files, etc.

FNR (NAWK/GAWK)

The FNR variable contains the number of lines read, but is reset for each file read. The NR variable accumulates for all files read. Therefore if you execute an awk script with two files as arguments, with each containing 10 lines:

nawk '{print NR}' file file2
nawk '{print FNR}' file file2

the first program would print the numbers 1 through 20, while the second would print the numbers 1 through 10 twice, once for each file.

OFMT (NAWK/GAWK)

The OFMT variable Specifies the default format for numbers. The default value is "%.6g."

RSTART, RLENGTH and match (NAWK/GAWK)

I've already mentioned the RSTART and RLENGTH variables. After the match() function is called, these variables contain the location in the string of the search pattern. RLENGTH contains the length of this match.

SUBSEP - Multi-dimensional array separator (NAWK/GAWK)

Earlier I described how you can construct multi-dimensional arrays in AWK. These are constructed by concatenating two indexes together with a special character between them. If I use an ampersand as the special character, I can access the value at location X, Y by the reference

array[ X "&" Y ]

NAWK (and GAWK) has this feature built in. That is, you can specify the array element

array[X,Y]

It automatically constructs the string, placing a special character between the indexes. This character is the non-printing character "034." You can control the value of this character, to make sure your strings do not contain the same character.

ENVIRON - environment variables (GAWK only)

The ENVIRON array contains the environment variables the current process. You can print your current search path using

print ENVIRON["PATH"]

IGNORECASE (GAWK only)

The IGNORECASE variable is normally zero. If you set it to non-zero, then all pattern matches ignore case. Therefore the following is equivalent to "grep -i match:"

BEGIN {IGNORECASE=1;}
/match/ {print}

CONVFMT - conversion format (GAWK only)

The CONVFMT variable is used to specify the format when converting a number to a string. The default value is "%.6g." One way to truncate integers is to convert an integer to a string, and convert the string to an integer - modifying the actions with CONVFMT:

a = 12;
b = a "";
CONVFMT = "%2.2f";
c = a "";

Variables b and c are both strings, but the first one will have the value "12.00" while the second will have the value "12."

ERRNO - system errors (GAWK only)

The ERRNO variable describes the error, as a string, after a call to the getline command fails.

FIELDWIDTHS - fixed width fields (GAWK only)

The FIELDWIDTHS variable is used when processing fixed width input. If you wanted to read a file that had 3 columns of data; the first one is 5 characters wide, the second 4, and the third 7, you could use substr to split the line apart. The technique, using FIELDWIDTHS, would be:

BEGIN {FIELDWIDTHS="5 4 7";}
{ printf("The three fields are %s %s %sn", $1, $2, $3);}



No comments: