Skip to Content
sed & awk, 2nd Edition
book

sed & awk, 2nd Edition

by Dale Dougherty, Arnold Robbins
March 1997
Intermediate to advanced
432 pages
11h 31m
English
O'Reilly Media, Inc.
Content preview from sed & awk, 2nd Edition

Using sed and awk Together

In UNIX, pipes can be used to pass the output from one program as input to the next program. Let’s look at a few examples that combine sed and awk to produce a report. The sed script that replaced the postal abbreviation of a state with its full name is general enough that it might be used again as a script file named nameState:

$ cat nameState
s/ CA/, California/
s/ MA/, Massachusetts/
s/ OK/, Oklahoma/
s/ PA/, Pennsylvania/
s/ VA/, Virginia/

Of course, you’d want to handle all states, not just five, and if you were running it on documents other than mailing lists, you should make sure that it does not make unwanted replacements.

The output for this program, using the input file list, is the same as we have already seen. In the next example, the output produced by nameState is piped to an awk program that extracts the name of the state from each record.

$ sed -f nameState list | awk -F, '{ print $4 }'
 Massachusetts
 Virginia
 Oklahoma
 Pennsylvania
 Massachusetts
 Virginia
 California
 Massachusetts

The awk program is processing the output produced by the sed script. Remember that the sed script replaces the abbreviation with a comma and the full name of the state. In effect, it splits the third field containing the city and state into two fields. “$4” references the fourth field.

What we are doing here could be done completely in sed, but probably with more difficulty and less generality. Also, since awk allows you to replace the string you match, you could achieve ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The AWK Programming Language, 2nd Edition

The AWK Programming Language, 2nd Edition

Alfred V. Aho, Brian W. Kernighan, Peter J. Weinberger

Publisher Resources

ISBN: 1565922255Supplemental ContentErrata Page