Sed Command Examples
Mastering Sed: Essential Stream Editor Commands
The sed command is a powerful stream editor for filtering and transforming text. It's widely used in Unix-like operating systems for performing basic text transformations on an input stream (a file or input from a pipeline). This page provides a collection of common and useful sed command examples to help you efficiently manipulate text data.
Find and Replace Text
The most frequent use of sed is for find and replace operations. The s command is used for substitution.
# To replace all occurrences of "day" with "night" and write to stdout:
sed 's/day/night/g' <file>
# To replace all occurrences of "day" with "night" within <file> (in-place edit):
sed -i 's/day/night/g' <file>
# To replace all occurrences of "day" with "night" on stdin:
echo 'It is daytime' | sed 's/day/night/g'
Text Cleaning and Formatting
sed is excellent for cleaning up text files, such as removing unwanted whitespace or empty lines.
# To remove leading spaces from each line:
sed -i -r 's/^\s+//g' <file>
# To remove empty lines and print results to stdout:
sed '/^$/d' <file>
# To replace newlines in multiple lines with a single space (useful for joining lines):
sed ':a;N;$!ba;s/\n/ /g' <file>
Inserting and Appending Text
You can use sed to insert lines before or after specific patterns.
# To insert a line before a matching pattern:
sed '/Once upon a time/i\Chapter 1' <file>
# To add a line after a matching pattern:
sed '/happily ever after/a\The end.' <file>
Further Resources
For more advanced usage and a deeper understanding of sed, consult the official documentation and community resources.
- GNU Sed Manual
- MDN Guide to Regular Expressions (Sed heavily relies on regex)
- Stack Overflow Sed Tag