Sed Cheatsheet

Stream editor for text transformations, substitution & filtering

Linux / Command
Contents
📝

Basics

# Basic syntax
sed 'command' file.txt            # print to stdout
sed -i 'command' file.txt          # edit in-place
sed -i.bak 'command' file.txt      # in-place with backup
sed -n 'command' file.txt          # suppress default output

# Print specific lines
sed -n '5p' file.txt               # line 5
sed -n '5,10p' file.txt            # lines 5-10
sed -n '$p' file.txt               # last line

# Pipe usage
echo "hello world" | sed 's/world/Sed/'
cat file.txt | sed 's/old/new/g'
🔄

Substitution

# Replace first occurrence per line
sed 's/old/new/' file.txt

# Replace all occurrences
sed 's/old/new/g' file.txt

# Case insensitive
sed 's/old/new/gi' file.txt

# Replace Nth occurrence
sed 's/old/new/2' file.txt         # 2nd match

# Different delimiter
sed 's|/usr/local|/opt|g' file.txt
sed 's#http://#https://#g' file.txt

# Backreferences
sed 's/\(.*\)@\(.*\)/User: \1, Domain: \2/' emails.txt

# Replace only on matching lines
sed '/error/s/old/new/g' file.txt

# Replace & print only changed lines
sed -n 's/old/new/gp' file.txt
✂️

Delete & Insert

# Delete line
sed '3d' file.txt                 # line 3
sed '$d' file.txt                 # last line
sed '3,5d' file.txt               # lines 3-5
sed '/pattern/d' file.txt         # matching lines
sed '/^$/d' file.txt              # empty lines
sed '/^#/d' file.txt              # comment lines

# Insert before line
sed '3i\New line text' file.txt

# Append after line
sed '3a\New line text' file.txt

# Replace entire line
sed '3c\Replacement line' file.txt
📍

Address Ranges

# Line number
sed '5s/old/new/'               # only line 5

# Range
sed '5,10s/old/new/'            # lines 5–10

# Pattern
sed '/START/,/END/s/old/new/'   # between patterns

# From pattern to end
sed '/START/,$s/old/new/'

# Every Nth line
sed '0~2s/old/new/'            # every 2nd line

# Not matching
sed '/pattern/!d'              # delete non-matching (like grep)
🚀

Advanced

# Multiple commands
sed -e 's/a/A/' -e 's/b/B/' file.txt
sed 's/a/A/; s/b/B/' file.txt

# Read from script file
sed -f commands.sed file.txt

# Append file content after match
sed '/MARKER/r insert.txt' file.txt

# Write matches to file
sed -n '/error/w errors.txt' file.txt

# Transliterate (like tr)
sed 'y/abc/ABC/' file.txt

# Hold space (multi-line)
sed 'N;s/\n/ /' file.txt         # join pairs of lines
💡

Common Examples

# Remove trailing whitespace
sed 's/[[:space:]]*$//' file.txt

# Remove leading whitespace
sed 's/^[[:space:]]*//' file.txt

# Add line numbers
sed '=' file.txt | sed 'N;s/\n/\t/'

# Extract between markers
sed -n '/BEGIN/,/END/p' file.txt

# Double-space a file
sed 'G' file.txt

# Remove HTML tags
sed 's/<[^>]*>//g' page.html

# Dos to Unix line endings
sed 's/\r$//' file.txt

# Replace in multiple files
find . -name "*.txt" -exec sed -i 's/old/new/g' {} +