Skip to main content

How to Delete with Sed

• 2 min read
bash sed delete lines stream editor text processing line removal

Quick Answer: Delete Lines with Sed

To delete a line, use sed '2d' file.txt to delete line 2 by number or sed '/pattern/d' file.txt to delete lines matching a pattern. For multiple deletions, combine patterns. The ‘d’ command is sed’s delete command.

Quick Comparison: Line Deletion Methods

SyntaxPurposeBest ForResult
’2d’Delete line numberSpecific linesDeletes only line 2
/pattern/dDelete matching patternPattern-basedAll matching lines
’2,5d’Delete rangeMultiple consecutiveLines 2-5
/start/,/end/dDelete between patternsBlock deletionFrom start to end

Bottom line: Use line numbers for specific lines; use patterns for flexible deletion.


Use sed to delete or remove lines from files based on patterns, line numbers, or conditions.

Method 1: Delete Specific Line by Number

# Delete line 2
sed '2d' file.txt

# Delete last line
sed '$d' file.txt

# Delete line 5 onwards
sed '5,$d' file.txt

Delete Line Range

# Delete lines 2-5
sed '2,5d' file.txt

# Delete lines 10 to end
sed '10,$d' file.txt

Detailed Example

Test file (data.txt):

Line 1: apple
Line 2: banana
Line 3: cherry
Line 4: date
Line 5: elderberry
# Delete line 2
sed '2d' data.txt

# Output:
# Line 1: apple
# Line 3: cherry
# Line 4: date
# Line 5: elderberry

# Delete lines 2-4
sed '2,4d' data.txt

# Output:
# Line 1: apple
# Line 5: elderberry

Delete Lines Matching Pattern

# Delete lines containing "pattern"
sed '/pattern/d' file.txt

# Delete lines starting with #
sed '/^#/d' file.txt

# Delete empty lines
sed '/^$/d' file.txt

# Delete lines with only whitespace
sed '/^[[:space:]]*$/d' file.txt

Delete Inverse (Keep Only Matching)

# Delete lines NOT containing pattern
sed '/pattern/!d' file.txt

# Delete lines NOT starting with #
sed '/^#/!d' file.txt

In-Place Deletion

# Delete and save to same file (with backup)
sed -i.bak '/pattern/d' file.txt

# Delete without backup
sed -i '/pattern/d' file.txt

Practical Example: Comment Removal

#!/bin/bash

# File: remove_comments.sh

input="$1"
output="${2:-clean.txt}"

# Remove comments and empty lines
sed -e '/^[[:space:]]*#/d' \
    -e '/^[[:space:]]*$/d' \
    "$input" > "$output"

echo "✓ Comments removed"
echo "Output: $output"

Usage:

$ chmod +x remove_comments.sh
$ ./remove_comments.sh config.conf clean.conf

Input (config.conf):

# Configuration file
server=localhost

# Port settings
port=8080

# Debug mode
debug=false

Output (clean.conf):

server=localhost
port=8080
debug=false

Delete Duplicate Empty Lines

# Keep only single empty lines
sed '/^$/N;/^\n$/!P;D' file.txt

# Or simpler: remove all extra blank lines
cat -s file.txt | sed '/^$/d'

Delete Lines Before/After Pattern

# Delete line before match
sed -e ':a' -e '$!{N;ba' -e '}' -e 's/[^\n]*\n//' file.txt

# Simpler: delete first line if contains "skip"
sed '0,/skip/{/skip/d;}' file.txt

Practical Example: Log Filtering

#!/bin/bash

# File: filter_log.sh

logfile="$1"
output="${2:-filtered.log}"

# Remove debug messages, empty lines, and INFO messages
sed -e '/DEBUG:/d' \
    -e '/^[[:space:]]*$/d' \
    -e '/INFO:/d' \
    "$logfile" > "$output"

echo "Filtered log saved to: $output"

Delete Specific Words (Not Lines)

# Replace words with nothing (delete words)
sed 's/word//g' file.txt

# Delete word at end of line
sed 's/ word$//' file.txt

Pattern Range Deletion

# Delete lines between two patterns
sed '/START/,/END/d' file.txt

# Delete from pattern to end of file
sed '/pattern/,$d' file.txt

# Delete from beginning to pattern
sed '1,/pattern/d' file.txt

Example:

Test file:

Keep this
DELETE START
Remove this line
Another remove
DELETE END
Keep this too
sed '/DELETE START/,/DELETE END/d' file.txt

# Output:
# Keep this
# Keep this too

Delete with Condition

# Delete if length > 80 characters
sed '/.\{80\}/d' file.txt

# Delete if contains numbers
sed '/[0-9]/d' file.txt

# Delete if starts with certain characters
sed '/^[0-9]/d' file.txt

Delete but Keep Count

#!/bin/bash

# Count and delete matching lines

pattern="$1"
file="$2"

count=$(grep -c "$pattern" "$file")
echo "Deleting $count lines matching: $pattern"

sed -i "/$pattern/d" "$file"
echo "✓ Complete"

Exclude Patterns

# Delete all lines except those containing "keep"
sed '/keep/!d' file.txt

# Delete lines not matching pattern
sed '/pattern/!d' file.txt

Combining Delete Operations

# Delete comments, empty lines, and blank-only lines
sed -e '/^[[:space:]]*#/d' \
    -e '/^[[:space:]]*$/d' \
    -e '/^$/d' file.txt

# More efficiently:
sed '/^[[:space:]]*\(#\|$\)/d' file.txt

Safe Deletion with Preview

#!/bin/bash

# Show what would be deleted before doing it

file="$1"
pattern="$2"

echo "=== Lines to be deleted ==="
sed -n "/$pattern/p" "$file"
echo ""

read -p "Continue with deletion? (y/n) " -r
if [[ $REPLY =~ ^[Yy]$ ]]; then
  sed -i "/$pattern/d" "$file"
  echo "✓ Deleted"
else
  echo "Cancelled"
fi

Common Mistakes

  1. Forgetting the d flag - sed '/pattern/' does nothing, need sed '/pattern/d'
  2. Escaping issues - special regex characters need escaping
  3. Using = instead of d - sed '2=' prints line number, not deletion
  4. Not backing up - always use -i.bak first time
  5. Wrong range syntax - use commas for ranges: 1,5 not 1-5

Performance Tips

  • Test with cat/grep before using -i
  • Use specific patterns when possible
  • Combine multiple -e expressions efficiently
  • For large files, consider using grep with -v

Key Points

  • Use d flag to delete lines
  • Line ranges: 2,5d for lines 2-5
  • Patterns: /pattern/d to delete matching
  • Use -i for in-place editing with backup
  • Always test before destructive operations

Summary

Sed’s delete function is powerful for cleaning files. Always test with a preview, use backups, and understand line ranges and patterns. Master pattern ranges for complex deletions.