sed Patterns

sed patterns I’ve actually used. Every entry has a date and context.

2026-03-07: Pipe Delimiter for Paths

Problem: Escaping hell with slashes in XML path substitution

Context: WLC VM migration, updating qemu paths in libvirt XML

The Fix:

# WRONG: escaping nightmare
sed -i 's/\/usr\/bin\/qemu-system-x86_64/\/usr\/libexec\/qemu-kvm/' file.xml

# RIGHT: use pipe delimiter
sed -i 's|/usr/bin/qemu-system-x86_64|/usr/libexec/qemu-kvm|' file.xml

Rule: When substituting paths, use | or # as delimiter instead of /

Worklog: WRKLOG-2026-03-07


2026-03-XX: In-Place Editing with Backup

Problem: Edit file in-place but keep a backup

Context: Config file modifications

The Fix:

# Create backup with .bak extension
sed -i.bak 's/old/new/g' file

# GNU sed: no backup (dangerous!)
sed -i 's/old/new/g' file

# BSD/macOS sed: backup required or use empty string
sed -i '' 's/old/new/g' file  # no backup on macOS

Rule: Always use -i.bak on production systems. Verify before deleting backup.

Worklog: Various


2026-03-XX: Delete Lines Matching Pattern

Problem: Remove all comment lines from config

Context: Cleaning up config files for comparison

The Fix:

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

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

# Delete both comments and empty lines
sed '/^#/d; /^$/d' file

# Delete lines containing pattern
sed '/pattern/d' file

Worklog: Various


2026-03-XX: Print Specific Line Range

Problem: Extract lines 100-110 from a file

Context: Examining specific section of log

The Fix:

# Print lines 100-110
sed -n '100,110p' file

# Print from line 100 to end
sed -n '100,$p' file

# Print line 100 and next 10 lines
sed -n '100,+10p' file

Note: For line ranges, prefer awk 'NR>=100 && NR⇐110' for practice.

Worklog: Various