Intermediate · 10 min · practise every command in the built-in terminal

sed — Stream Editor

sed processes text line by line. It's incredibly powerful for find-and-replace and transformations.

Substitute (most common)

sed 's/old/new/' file.txt         # Replace first occurrence per line
sed 's/old/new/g' file.txt        # Replace all occurrences (global)
sed 's/old/new/i' file.txt        # Case-insensitive
sed 's/old/new/2' file.txt        # Replace 2nd occurrence only

Edit in-place

sed -i 's/old/new/g' file.txt     # Modify file directly
sed -i.bak 's/old/new/g' file.txt # Modify and create .bak backup

Delete lines

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

Print specific lines

sed -n '5p' file.txt              # Print line 5
sed -n '2,8p' file.txt            # Print lines 2-8
sed -n '/pattern/p' file.txt      # Print matching lines

Practical examples

# Change all http to https in a config file
sed -i 's/http:/https:/g' config.txt

# Remove blank lines from a file
sed '/^$/d' file.txt

# Remove leading whitespace
sed 's/^[ \t]*//' file.txt

Practice tasks

  1. Create a file with 'Hello World', then use sed to replace 'World' with 'Linux'
  2. Delete all empty lines from a file using sed
  3. Replace all occurrences of a word (not just the first) in a file
  4. Print only line 2 of a file using sed

Commands in this lesson

Text Processing