sed Comprehensive Examples

Basic Syntax

sed [OPTIONS] 'COMMAND' file.txt

1. Substitution (s command)

Replace first occurrence per line:

sed 's/apple/orange/' fruits.txt

Replace all occurrences (global):

sed 's/apple/orange/g' fruits.txt

Case-insensitive replacement:

sed 's/apple/orange/gi' fruits.txt

Replace specific occurrence:

# Replace 2nd occurrence in each line
sed 's/apple/orange/2' fruits.txt

With regex groups:

# Rearrange date format from YYYY-MM-DD to DD/MM/YYYY
sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\3\/\2\/\1/' dates.txt

2. Deletion (d command)

Delete specific line:

# Delete 3rd line
sed '3d' file.txt

Delete range of lines:

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

Delete pattern-matched lines:

# Delete lines containing "error"
sed '/error/d' logfile.txt

Delete empty lines:

sed '/^$/d' file.txt

3. Insertion/Appending (i/a commands)

Insert line before match:

# Add header before line 1
sed '1i\FRUIT LIST' fruits.txt

Append line after match:

# Add footer after last line
sed '$a\END OF LIST' fruits.txt

4. Printing (p command)

Print only modified lines:

sed -n 's/error/warning/p' logfile.txt

Print specific lines:

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

5. In-place Editing

Edit file directly (with backup):

sed -i.bak 's/foo/bar/g' file.txt

Edit without backup:

sed -i '' 's/foo/bar/g' file.txt  # macOS/BSD
sed -i 's/foo/bar/g' file.txt     # Linux

6. Address Ranges

Between line numbers:

# Replace in lines 10-20
sed '10,20s/old/new/g' file.txt

Between patterns:

# Replace between START and END markers
sed '/START/,/END/s/foo/bar/g' file.txt

Advanced Examples

Multiple commands:

sed -e 's/foo/bar/g' -e '/baz/d' file.txt

Edit HTML tags:

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

Number lines:

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

Swap adjacent words:

sed -E 's/([a-z]+) ([a-z]+)/\2 \1/' text.txt

Convert CSV to TSV:

sed 's/,/\t/g' data.csv

Convert DOS to UNIX line endings:

sed 's/\r$//' dosfile.txt > unixfile.txt

Transform case:

sed 's/.*/\L&/g'  # All lowercase
sed 's/.*/\U&/g'  # All uppercase

Tips

  1. Use -E (or -r) for extended regular expressions
  2. Combine with grep/awk for complex pipelines
  3. Test commands with -n and p before in-place edits
  4. Use & in replacement to reference entire match
  5. Escape special characters (/, &, \) with backslash

Create test file:

echo -e "apple\nbanana\ncherry\ndate\napple\nfig" > fruits.txt

Note: sed is line-oriented and follows this processing cycle:

  1. Read line into pattern space
  2. Apply commands
  3. Print pattern space
  4. Repeat