Keeping Some Output, Discarding the Rest
Problem
You need a way to keep some of your output and discard the rest.
Solution
The following code prints the first word of every line of input:
$ awk '{print $1}' myinput.file
Words are delineated by whitespace. The awk utility reads data from the filename supplied on the command line, or from standard input if no filename is given. Therefore, you can redirect the input from a file, like this:
$ awk '{print $1}' < myinput.file
or even from a pipe, like this:
$ cat myinput.file | awk '{print $1}'
Discussion
The awk program can be used in several different ways. Its easiest, simplest use is just to print one or more selected fields from its input.
Fields are delineated by whitespace (or specified with the -F
option) and are
numbered starting at 1. The field $0 represents the entire line of
input.
awk is a complete programming language; awk scripts can become extremely complex. This is only the beginning.
See Also
man awk
Effective awk Programming by Arnold Robbins (O’Reilly)
sed & awk by Arnold Robbins and Dale Dougherty (O’Reilly)
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.