Back to Blog

Zsh Tutorial: sed Substitution, Patterns & Practical Commands #18

Sandy LaneSandy Lane

Video: Zsh Tutorial: sed Substitution, Patterns & Practical Commands #18 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Zsh Tutorial: sed Substitution, Patterns & Practical Commands

This tutorial explores how to use sed in Zsh for powerful text processing. It covers substitution commands, pattern matching, line addressing, and practical editing techniques such as in-place file modification and multi-command usage.

Code

# Basic substitution: replace 'old' with 'new' in a file
sed 's/old/new/' filename.txt

# Global replacement (all occurrences on each line)
sed 's/old/new/g' filename.txt

# Case-insensitive replacement
sed 's/old/new/Ig' filename.txt

# In-place editing (modify file directly)
sed -i '' 's/old/new/g' filename.txt

# Using alternate delimiters to avoid escaping slashes
sed 's|/usr/bin|/usr/local/bin|g' filename.txt

# Print only line 3
sed -n '3p' filename.txt

# Print lines 2 to 4
sed -n '2,4p' filename.txt

# Print lines matching a pattern (e.g., lines containing "error")
sed -n '/error/p' filename.txt

# Print lines from pattern "start" to "end"
sed -n '/start/,/end/p' filename.txt

# Print all lines except those starting with '#'
sed -n '/^#/!p' filename.txt

# Delete lines matching a pattern (e.g., blank lines)
sed '/^$/d' filename.txt

# Insert a line before line 2
sed '2i\
Inserted line before line 2' filename.txt

# Append a line after line 3
sed '3a\
Appended line after line 3' filename.txt

# Multiple commands: delete blank lines and replace 'foo' with 'bar'
sed -e '/^$/d' -e 's/foo/bar/g' filename.txt

# Using a pipe to send output to sed for processing
cat filename.txt | sed 's/old/new/g'

Key Points

  • sed substitution uses the syntax s/old/new/ with optional flags like g for global and I for case-insensitive.
  • Line addressing and pattern matching allow selective editing or printing of specific lines or ranges.
  • In-place editing with -i modifies files directly without needing temporary files.
  • Alternate delimiters simplify substitutions when the pattern contains slashes or other special characters.
  • Multiple commands can be combined using -e flags or semicolons for complex text transformations.