Fundamentals 4 min read

How to Delete Lines in Files Using sed on Linux

This guide explains how to use the Linux sed command to delete specific lines, line ranges, empty lines, or lines matching a pattern, and shows how to apply changes directly to the original file with the –i option, including example commands and cautions.

Liangxu Linux
Liangxu Linux
Liangxu Linux
How to Delete Lines in Files Using sed on Linux

Introduction

In Linux, sed is a powerful text‑processing utility that can delete lines from a file. The following sections demonstrate common ways to remove lines using sed .

Delete a Specific Line

To delete a particular line number, use:
sed 'nd' filename
Replace n with the line number. For example, to delete line 3:
sed '3d' filename

Delete a Range of Lines

To delete a continuous range, specify the start and end line numbers separated by a comma:
sed '3,5d' filename

Delete Empty Lines

To remove all blank lines:
sed '/^$/d' filename
The pattern ^$ matches an empty line, and /pattern/d deletes lines that match the pattern.

Delete Lines Matching a Pattern

To delete any line that contains a specific pattern:
sed '/pattern/d' filename
Replace pattern with the desired regular expression; /pattern/d removes all matching lines.

Modify the Original File In‑Place

By default, sed writes the result to standard output. Use the -i option to edit the file directly:
sed -i 'nd' filename
For example, to delete line 3 in place:
sed -i '3d' filename
Be careful with -i because it overwrites the original file.

Conclusion

These commands cover the basic methods for deleting lines with sed . The tool also offers many advanced features; consult the sed documentation for further capabilities.
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.

command-linetext processingfile editingsed
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.