Last updated
GNU sed vs BSD sed (macOS) Differences
- In-place editing: GNU uses
-i ''or-i; BSD requires-i ''(with empty string) - Extended regex: both support
-E, but GNU also accepts-r - Step addresses (
first~step) are GNU-only - The
\wword character shorthand works in GNU sed but not always in BSD sed
Common Use Cases
- Replacing configuration values across multiple files
- Stripping comments and blank lines from config files
- Transforming CSV or log file formats
- Updating version numbers in source files during CI/CD
- Extracting specific sections from large text files
- Batch renaming patterns in code files
Examples
Example 1: Basic Substitution
Replace the first occurrence of a word on each line:
sed 's/foo/bar/' file.txt
Replace all occurrences on each line (global flag):
sed 's/foo/bar/g' file.txt
Case-insensitive replacement (GNU sed):
sed 's/foo/bar/gi' file.txt
Replace and edit the file in place (GNU sed):
sed -i 's/foo/bar/g' file.txt
In-place edit with backup (macOS/BSD sed):
sed -i '.bak' 's/foo/bar/g' file.txt
Example 2: Delete Lines
Delete blank lines:
sed '/^$/d' file.txt
Delete lines containing a specific pattern:
sed '/TODO/d' file.txt
Delete comment lines starting with #:
sed '/^#/d' file.txt
Delete a specific line number (line 5):
sed '5d' file.txt
Delete a range of lines (lines 3 through 7):
sed '3,7d' file.txt
Delete from a pattern to end of file:
sed '/^END/,$d' file.txt
Example 3: Print Specific Lines
Print only lines matching a pattern (like grep):
sed -n '/error/p' file.txt
Print lines 10 through 20:
sed -n '10,20p' file.txt
Print from a pattern to another pattern:
sed -n '/START/,/END/p' file.txt