SED Commands Cheatsheet — Essential Reference
Sed (Stream EDitor) is a powerful command-line utility for parsing and transforming text. It is commonly used for tasks like find and replace, text manipulation, and filtering.
RECOMMENDED
Master SED with Top Reference Books
Level up your DevOps skills. Find the best guide books and cheatsheet references for your engineering stack.
Commands
| Command | Description | Example |
|---|---|---|
sed 's/pattern/replacement/' file.txt |
Substitute the first occurrence of 'pattern' with 'replacement' on each line. | sed 's/old_word/new_word/' document.txt |
sed 's/pattern/replacement/g' file.txt |
Substitute all occurrences of 'pattern' with 'replacement' on each line (global). | sed 's/error/warning/g' logfile.log |
sed -n '/pattern/p' file.txt |
Print only lines matching 'pattern' (suppress normal output with -n). | sed -n '/important_data/p' report.csv |
sed '/pattern/d' file.txt |
Delete lines matching 'pattern'. | sed '/^#/d' config.ini |
sed -i 's/pattern/replacement/g' file.txt |
Edit file in-place (modifies the original file). Use -i.bak for a backup. | sed -i.bak 's/http/https/g' website_links.txt |
sed '1,5d' file.txt |
Delete lines from 1 to 5 (inclusive). | sed '1,10d' large_file.txt |
sed '/start_pattern/,/end_pattern/d' file.txt |
Delete lines within a range defined by two patterns. | sed '/BEGIN_BLOCK/,/END_BLOCK/d' code.py |
sed -E 's/([0-9]+)-([0-9]+)/\2-\1/g' file.txt |
Use extended regular expressions (-E) for more powerful pattern matching and back-references. | sed -E 's/([A-Za-z]+) ([A-Za-z]+)/\2, \1/' names.txt |
Pro Tips
- Always test your `sed` commands on a copy of the file or use the `-i.bak` option to create a backup before modifying files in-place.
- Combine `sed` with pipes (`|`) to create powerful text processing pipelines with other commands like `grep`, `awk`, and `sort`.
- Understand the difference between basic regular expressions (BRE) and extended regular expressions (ERE) and use `-E` when EREs are more convenient.
Frequently Asked Questions
What is sed used for?
Sed is primarily used for text transformation and filtering. It can perform operations like substitution, deletion, insertion, and printing of lines based on patterns.
How do I install sed?
Sed is a standard Unix utility and is pre-installed on virtually all Linux and macOS systems. For Windows, you can get it as part of Cygwin or Git Bash.