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.
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' filenameReplace n with the line number. For example, to delete line 3:
sed '3d' filenameDelete a Range of Lines
To delete a continuous range, specify the start and end line numbers separated by a comma:
sed '3,5d' filenameDelete Empty Lines
To remove all blank lines:
sed '/^$/d' filenameThe 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' filenameReplace 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' filenameFor example, to delete line 3 in place:
sed -i '3d' filenameBe 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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
