(gawk) One-liners
Info Catalog
(gawk) Getting Started
(gawk) Top
(gawk) Regexp
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 Info file 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'.
Since you are reading this in Info, each line of the example code is
enclosed in quotes, to represent text that you would type literally.
The examples themselves represent shell commands that use single quotes
to keep the shell from interpreting the contents of the program. When
reading the examples, focus on the text between the open and close
quotes.
`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.
Info Catalog
(gawk) Getting Started
(gawk) Top
(gawk) Regexp
automatically generated byinfo2html