Skip to main content
sed is a powerful stream editor for transforming text on the command line. In this guide, you’ll learn how to use the p (print) script to display lines selectively, control automatic output, and integrate sed into complex pipelines. Whether you’re filtering log files or extracting specific records, mastering sed’s I/O model is essential for efficient command-line workflows.

Unix I/O Model

sed’s Default Behavior

By default, sed processes text from stdin or listed files and writes each line to stdout, applying any provided scripts. Typing:
reads from stdin and applies the p (print) script to every line. Example:
Output:
Explanation:
  1. sed reads each line into the pattern space.
  2. The p script prints it immediately.
  3. Without disabling automatic printing, sed outputs the line again after processing.

Syntax Overview

The image shows a command-line syntax for the sed command, specifically highlighting the use of the print (p) script.

Using sed with Pipes and Files

Piping Input

Output:

Reading from a File

Output:
In this case, sample.txt replaces stdin as sed’s input source.

Selecting Specific Lines

sed supports addresses (such as line numbers) to target scripts.
Output:
Explanation:
  • Line 2 matches 2p, so it’s printed by the script and then automatically once more.
Use single quotes (') around sed scripts to prevent the shell from interpreting special characters.

Suppressing Automatic Printing

To output only the lines you explicitly match, use the -n option.
Output:
Forgetting -n can lead to duplicate lines when using print scripts.

Real-World Example: Filtering Command Output

Extract the third line from the df -h display:
Apply sed:
Result:

Working with a Data File

Consider an employees.txt file with pipe-delimited records:
The image shows a text file named "employees.txt" containing a list of employees with details such as name, department, job title, email, and salary.
To print the fifth record only:
Output:

Summary

  • sed reads from stdin or listed files by default.
  • Enclose scripts in single quotes to avoid shell expansion.
  • Use addresses (e.g., 2p) to target specific lines.
  • The -n option disables automatic printing for precise control.
  • Place input files after the script.
In upcoming lessons, we’ll cover additional sed commands:
  • d delete lines
  • s substitute text
  • i insert text

References

Watch Video