sed Quickstart Guide

Introduction

sed (Stream EDitor) is a powerful text processing tool for:

  • Parsing and transforming text
  • Performing substitutions
  • Filtering content
  • Non-interactive text editing

Basic Syntax

sed [options] 'script' inputfile

Common Options

  • -i: Edit files in-place (dangerous but useful)
  • -E: Use extended regular expressions
  • -n: Suppress automatic printing
  • -e: Add multiple commands

Common Operations

1. Substitution (s command)

# Basic replacement
sed 's/apple/orange/' file.txt

# Global replacement (all occurrences)
sed 's/apple/orange/g' file.txt

# Case-insensitive replacement
sed 's/apple/orange/gi' file.txt

2. Addresses (Line Selection)

# Replace only on line 5
sed '5s/apple/orange/' file.txt

# Replace between lines 3-7
sed '3,7s/apple/orange/' file.txt

# Replace lines containing "error"
sed '/error/s/apple/orange/' file.txt

3. Delete Lines (d command)

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

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

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

4. Print Specific Lines (p command)

# Print only lines containing "error"
sed -n '/error/p' file.txt

# Print lines 10-15
sed -n '10,15p' file.txt

5. In-place Editing

# Edit file and create backup
sed -i.bak 's/apple/orange/g' file.txt

# Edit without backup (dangerous)
sed -i 's/apple/orange/g' file.txt

Advanced Usage

Multiple Commands

sed -e 's/apple/orange/' -e '/banana/d' file.txt

Using Files as Scripts

# script.sed
s/apple/orange/g
/error/d
s/foo/bar/g

sed -f script.sed file.txt

Regular Expressions

# Capture groups (use \1, \2 etc)
sed -E 's/(.*): (.*)/User: \1, Email: \2/'

# Match word boundaries
sed 's/\bapple\b/orange/g'

Examples

  1. Replace all occurrences of "colour" with "color":
sed 's/colour/color/g' file.txt
  1. Delete comments from config file:
sed '/^#/d' config.conf
  1. Swap first and second columns:
sed -E 's/^([^ ]+) ([^ ]+)/\2 \1/' data.txt
  1. Convert DOS line endings to UNIX:
sed 's/\r$//' dosfile.txt > unixfile.txt
  1. Extract lines between two patterns:
sed -n '/START/,/END/p' logfile.txt

Tips

  • Always test commands without -i first
  • Use & to represent the matched pattern in replacement
  • Combine with grep and awk for complex pipelines
  • Escape special characters: .*[\^$

Note: sed processes text line by line, making it very efficient for large files.