0
0
Linux-cliHow-ToBeginner · 3 min read

How to Use sed Command in Linux: Syntax and Examples

The sed command in Linux is a stream editor used to perform basic text transformations on input streams or files. You use it by specifying a script or command like sed 's/old/new/' file to replace text. It is powerful for automated editing in scripts and command line.
📐

Syntax

The basic syntax of the sed command is:

  • sed [options] 'script' inputfile
  • script contains editing commands like substitution.
  • inputfile is the file to process; if omitted, sed reads from standard input.

Common parts of the script include:

  • s/pattern/replacement/flags: substitute pattern with replacement.
  • g flag: replace all occurrences in a line.
  • -i option: edit files in place.
bash
sed 's/old-text/new-text/' filename
💻

Example

This example replaces the first occurrence of the word apple with orange in each line of the file fruits.txt:

bash
cat > fruits.txt <<EOF
apple banana apple
banana apple cherry
EOF

sed 's/apple/orange/' fruits.txt
Output
orange banana apple banana orange cherry
⚠️

Common Pitfalls

Common mistakes when using sed include:

  • Forgetting the g flag to replace all matches on a line, so only the first match changes.
  • Not using quotes around the script, causing shell interpretation errors.
  • Using -i without a backup suffix can overwrite files without recovery.

Example of wrong and right usage:

bash
sed s/apple/orange/ fruits.txt  # Wrong: no quotes, may cause errors
sed 's/apple/orange/g' fruits.txt  # Right: quotes and global flag
📊

Quick Reference

CommandDescription
sed 's/old/new/' fileReplace first occurrence of 'old' with 'new' in each line
sed 's/old/new/g' fileReplace all occurrences of 'old' with 'new' in each line
sed -i 's/old/new/' fileEdit file in place, replacing first occurrence
sed -n 'p' filePrint lines (useful with other commands)
sed '/pattern/d' fileDelete lines matching 'pattern'

Key Takeaways

Use sed 's/old/new/' file to replace text in files or streams.
Add the g flag to replace all matches on a line, not just the first.
Use quotes around the script to avoid shell errors.
Use -i to edit files directly but be cautious to avoid data loss.
Test your sed commands without -i first to verify output.