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.
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' filenameDelete 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' filenameDelete Lines Matching a Pattern
Delete any line that contains a given pattern by using the pattern before the d command:
sed '/pattern/d' filenameIn‑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.
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.
