Fundamentals 3 min read

Master Deleting Lines with sed: Simple Commands for Precise Text Editing

Learn how to use the powerful Linux sed command to delete specific lines, ranges, empty lines, or pattern‑matched lines from a file, including in‑place editing with the -i option, through clear examples and step‑by‑step syntax.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Master Deleting Lines with sed: Simple Commands for Precise Text Editing

Using sed to Delete Lines

sed is a versatile stream editor in Linux for text manipulation. This guide shows how to delete lines in various ways.

Delete Specific Lines

To delete a single line, use the line number with the d command: sed '3d' filename Replace 3 with the desired line number.

To delete a range of lines, specify start and end numbers separated by a comma:

sed '3,5d' filename

Delete Empty Lines

Remove all blank lines with a regular expression that matches the start and end of a line with nothing between them:

sed '/^$/d' filename

Delete Lines Matching a Pattern

Delete any line that contains a given pattern by using the pattern before the d command:

sed '/pattern/d' filename

In‑Place Editing

By default, sed writes the result to standard output. To modify the original file directly, add the -i option: sed -i '3d' filename Be cautious with -i because it overwrites the file without prompting.

For more advanced text processing, consult the sed manual for additional commands and options.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

LinuxShellcommand-linesedtext-processing
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.