General Text Selection: awk



next up previous contents index
Next: Shell Programs (Scripts) Up: Unix Toolkit Previous: Unix's File Editor:

General Text Selection: awk

The awk command is another text selection and manipulation tool. Some call it the most popular Unix tool of its type, while others call it incomprehensible and awkward. We have heard rumors that there are users who write 500-line awk scripts and still function in polite society, but we doubt it. Personally we use awk only in situations where we can't get other Unix tools like sed and grep to work. In its simplest form, awk selects a line from a file according to some pattern, like grep, but is much more general. We present here a few examples of awk but refer interested readers to the References for more information.   

The form of an awk command is:

% awd pattern {action}   	Generic awk.   

One of the more useful tricks of awk is to be able to select all text between two patterns. For example, select all lines in an output file between the words Gaussian points and Gaussian weights, you use a command like this:

% awk "/Gaussian points/,/Gaussian weights/" output.dat   	   

To see more of the power of awk, here we print out each line in a file for which the previous line starts with zk(1):

% awk ' prev =="zk(1),"{print} {prev=$1}' output.dat   	   

In this last example, you will notice that every time a line is read, the first pattern on the line $1 is assigned to the variable prev. Then when the next line is read, the pattern prev =="zk(1)," is tested. If the pattern is true, then the action {print} is taken and the line is printed. You will also notice that the next action {prev=$1} does not have a pattern before it and therefore is always taken. The two awk pattern-action pairs are surrounded with single quotes to group them as a single option to awk.



next up previous contents index
Next: Shell Programs (Scripts) Up: Unix Toolkit Previous: Unix's File Editor: