DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Programming with awk

A handful of useful one-liners

Although awk can be used to write large programs of some complexity, many programs are not much more complicated than what we've seen so far. Here is a collection of other short programs that you may find useful and instructive. Although these programs are not explained here, new constructs they may contain are discussed later in this topic.

Print last field of each input line:

   { print $NF }

Print 10th input line:

   NR == 10

Print last input line:

   	{ line = $0}
   END	{ print line }

Print input lines that do not have four fields:

   NF != 4    { print $0, "does not have 4 fields" }

Print input lines with more than four fields:

   NF > 4
Print input lines with last field more than 4:
   $NF > 4
Print total number of input lines:
   END	{ print NR }

Print total number of fields:

   	{ nf = nf + NF }
   END	{ print nf }

Print total number of input characters:

   	{ nc = nc + length($0) }
   END	{ print nc + NR }
(Adding NR includes in the total the number of newlines.)

Print the total number of lines that contain the string Asia:

   /Asia/	{ nlines++ }
   END	{ print nlines }
(nlines++ has the same effect as nlines = nlines + 1.)
Next topic: Error messages
Previous topic: Functions

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004