Home > Text Processing & Search > sed

sed -n: Print Specific Lines Only

sed is a stream editor used for editing text files or text streams passed through a pipe. The '-n' option, in particular, suppresses sed's default behavior of printing all lines (outputting the content of the pattern space) and only prints lines for which a 'p' (print) command is explicitly specified, making it very useful for extracting specific lines. It functions similarly to grep but allows for more complex text transformations and extractions.

Overview

The sed command is a powerful tool for editing text streams. The '-n' option disables sed's default behavior of printing all lines, allowing users to selectively print only the desired lines through specific commands like 'p' (print). This enables precise text processing in various scenarios such as log file analysis and specific data extraction.

Key Features

  • Suppresses default output
  • Selectively prints specific lines
  • Pattern matching based on regular expressions
  • Can use script files

Key Options

The sed command offers various options, but here we explain those commonly used with the '-n' option.

Output Control and Pattern Matching

Generated command:

Try combining the commands.

Description:

`sed` Executes the command.

Combine the above options to virtually execute commands with AI.

Usage Examples

Various text processing examples using sed -n.

Print Specific Line

sed -n '5p' filename.txt

Prints only the 5th line of a file.

Print Specific Range of Lines

sed -n '10,20p' filename.txt

Prints lines from the 10th to the 20th line of a file.

Print Lines Matching a Regular Expression

sed -n '/error/p' logfile.log

Prints only lines containing the string 'error'.

Substitute Matching Line and Print

sed -n 's/old/new/p' filename.txt

Prints only lines where 'old' is substituted with 'new'.

Print Only the First Matching Line

sed -n '/pattern/{p;q}' filename.txt

Prints only the first line matching the pattern and then exits sed.

Remove Blank Lines and Print

sed -n '/^$/!p' filename.txt

Prints only non-blank lines from a file.

Tips & Precautions

Useful tips and points to note when using sed -n.

Difference from grep

  • grep simply outputs lines that match a pattern, whereas sed -n can perform additional edits (like substitution) on matched lines before printing.
  • sed -n can handle more complex conditions than grep (e.g., pattern matching only within a specific line range).

Performance Considerations

When processing large files, sed reads and processes the file line by line, making it memory-efficient. However, complex regular expressions can impact performance.

Frequently Used Patterns

  • 'p': Print matched line
  • 's/regex/replacement/': Substitute matched part
  • 'd': Delete matched line (Note: when used with '-n', 'd' removes the line from the pattern space, so if there's no 'p' command, nothing will be printed)

Same category commands