Go to the first, previous, next, last section, table of contents.

# Useful One Line Programs

Many useful `awk` programs are short, just a line or two. Here is a collection of useful, short programs to get you started. Some of these programs contain constructs that haven't been covered yet. The description of the program will give you a good idea of what is going on, but please read the rest of the book to become an `awk` expert!

Most of the examples use a data file named ``data'`. This is just a placeholder; if you were to use these programs yourself, you would substitute your own file names for ``data'`.

`awk '{ if (length($0) > max) max = length($0) }`
`END { print max }' data`
  This program prints the length of the longest input line.
`awk 'length($0) > 80' data`
  This program prints every line that is longer than 80 characters. The sole rule has a relational expression as its pattern, and has no action (so the default action, printing the record, is used).
`expand data | awk '{ if (x < length()) x = length() }`
`END { print "maximum line length is " x }'`
  This program prints the length of the longest line in ``data'`. The input is processed by the `expand` program to change tabs into spaces, so the widths compared are actually the right-margin columns.
`awk 'NF > 0' data`
  This program prints every line that has at least one field. This is an easy way to delete blank lines from a file (or rather, to create a new file similar to the old file but from which the blank lines have been deleted).
`awk 'BEGIN { for (i = 1; i <= 7; i++)`
`print int(101 * rand()) }'`
  This program prints seven random numbers from zero to 100, inclusive.
`ls -lg files | awk '{ x += $5 } ; END { print "total bytes: " x }'`
  This program prints the total number of bytes used by files.
`ls -lg files | awk '{ x += $5 }`
`END { print "total K-bytes: " (x + 1023)/1024 }'`
  This program prints the total number of kilobytes used by files.
`awk -F: '{ print $1 }' /etc/passwd | sort`
  This program prints a sorted list of the login names of all users.
`awk 'END { print NR }' data`
  This program counts lines in a file.
`awk 'NR % 2 == 0' data`
  This program prints the even numbered lines in the data file. If you were to use the expression ``NR % 2 == 1'` instead, it would print the odd numbered lines.

Go to the first, previous, next, last section, table of contents.