sed) is a powerful command-line utility for transforming text in a pipeline. In this guide, we’ll explore how to delete lines from input files using the d command, covering non-destructive edits, specific-line removals, range deletions, and in-place updates.
Table of Contents
- Overview of the
dCommand - Non-Destructive Deletion
- Deleting a Specific Line
- Deleting a Range of Lines
- In-Place Deletion with
-i - Quick Reference
- Links & References
Overview of the d Command
The simplest way to remove lines in sed is with the delete script d:
sed follows this syntax:
- SCRIPT: A quoted set of editing commands (here,
'd'). - INPUT-FILE: One or more files to process (defaults to standard input).
Wrap your script in single quotes (e.g.,
'd') so the shell interprets it literally.Non-Destructive Deletion
By default,sed writes the transformed text to standard output and leaves the original file unchanged. To delete line 2 from employees.txt:
Deleting a Specific Line
To drop only the sixth line:Deleting a Range of Lines
Use a comma-separated address pair to remove a block of lines:Address ranges must ascend (e.g.,
3,5d). Specifying 5,3d is invalid and will have no effect.In-Place Deletion with -i
To modify the file directly, add the -i (in-place) option:
On macOS,
sed -i requires a zero-length extension: sed -i '' '2,7d' file.txt. Always back up critical data before in-place edits.Quick Reference
| Command Syntax | Effect | Example |
|---|---|---|
sed 'd' | Delete all lines | sed 'd' employees.txt |
sed 'Nd' | Delete Nth line | sed '6d' employees.txt |
sed 'M,Nd' | Delete line range | sed '3,5d' employees.txt |
sed -i 'M,Nd' | In-place deletion | sed -i '2,7d' employees.txt |