sed -n p: Print Only Selected Lines
sed -n turns off automatic printing so the p command prints only the lines you choose.
By default sed prints every line. Add -n and sed prints nothing unless you ask it to with p, turning sed into a precise line selector.
What it does
The -n flag suppresses sed automatic per-line printing. The p command then explicitly prints the current line. Together they emit only addressed lines. Without -n, p prints matching lines twice because auto-print still fires.
Common usage
sed -n '5p' file # print only line 5
sed -n '10,20p' file # print lines 10-20
sed -n '/error/p' app.log # print lines matching error
sed -n '$p' file # print the last line
sed -n '1,/END/p' file # print from line 1 to first ENDOptions
| Piece | What it does |
|---|---|
| -n | Suppress automatic printing of every line |
| p | Print the current pattern space |
| Np | Print line number N |
| M,Np | Print the range M to N |
| /regex/p | Print lines matching the regex |
| p without -n | Prints matched lines twice (auto-print plus p) |
In CI
sed -n is the portable way to extract a line range from a log or config, equivalent across GNU and BSD. To pull a single value, combine with substitution: sed -n 's/^version=//p' reads and trims in one pass.
Common errors in CI
If output is doubled, -n was omitted and both auto-print and p fired. sed: -e expression #1, char N: extra characters after command means something followed p on the same expression without a semicolon or newline, for example 5p6 instead of 5p;6p.