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' inputfilescriptcontains editing commands like substitution.inputfileis the file to process; if omitted,sedreads from standard input.
Common parts of the script include:
s/pattern/replacement/flags: substitutepatternwithreplacement.gflag: replace all occurrences in a line.-ioption: edit files in place.
bash
sed 's/old-text/new-text/' filenameExample
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.txtOutput
orange banana apple
banana orange cherry
Common Pitfalls
Common mistakes when using sed include:
- Forgetting the
gflag to replace all matches on a line, so only the first match changes. - Not using quotes around the script, causing shell interpretation errors.
- Using
-iwithout 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 flagQuick Reference
| Command | Description |
|---|---|
| sed 's/old/new/' file | Replace first occurrence of 'old' with 'new' in each line |
| sed 's/old/new/g' file | Replace all occurrences of 'old' with 'new' in each line |
| sed -i 's/old/new/' file | Edit file in place, replacing first occurrence |
| sed -n 'p' file | Print lines (useful with other commands) |
| sed '/pattern/d' file | Delete 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.