DispersedNetUNIX Shell Programming

Lesson 6

Print Selected Lines with sed

Objective: Use -n and explicit printing to select records.

The p instruction explicitly prints pattern space. Automatic printing remains enabled unless you request -n. Combining -n with addressed p instructions is therefore a clear way to output only selected lines; p is valid without -n, but matching lines may appear twice.

sed -n '2,5p' petchip

This prints four records, from Maisey through Milo. The endpoints are included. Other lines are read but not printed. The -n option belongs to the sed command line, outside the quoted script.

Select by content

sed -n '/:cat:/p' petchip

This prints the five cat records in the supplied fixture. Including colons avoids matching cat inside a longer word. A simple pattern address searches anywhere in the line unless anchors restrict it.

A line number is not a search pattern

sed -n '5p' petchip
sed -n '/5/p' petchip

The first prints only input line 5, the Milo record. The second prints any record containing the character 5 anywhere, including a date, numeric field, or identifier. The slash delimiters distinguish a regular-expression address from a numeric address.


Understand duplicate output

printf '%s\n' 'cat' 'dog' | sed '/cat/p'

The output is cat, cat, then dog. One cat is explicit output from p; the other cat and dog come from normal end-of-cycle printing. Add -n when only the explicit output is wanted. Overlapping explicit print instructions can still print a line more than once even with -n.

To print only lines on which a substitution succeeds, use the substitution’s p flag with -n:

sed -n 's/:cat:/:feline:/p' petchip

This both transforms and selects output. It is different from printing every line after a substitution. Before using such output elsewhere, check whether downstream consumers expect all input records or only the changed subset.