Bash
sed
sed stream editor commands for text transformation.
27 commands
Windows
MacOS
Linux
#text-processing
#stream-editor
Substitution
Replace first occurrence per line
sed 's/old/new/' file.txt
Replace all occurrences per line
sed 's/old/new/g' file.txt
Replace all, case-insensitive
sed 's/old/new/gi' file.txt
Replace only on line 3
sed '3s/old/new/' file.txt
Replace on lines 2 through 5
sed '2,5s/old/new/g' file.txt
Use alternate delimiter for paths
sed 's|/usr/bin|/opt/bin|g' file.txt
Deletion
Delete line 5
sed '5d' file.txt
Delete lines 2 through 4
sed '2,4d' file.txt
Delete lines matching a pattern
sed '/pattern/d' file.txt
Delete empty lines
sed '/^$/d' file.txt
Delete comment lines starting with hash
sed '/^#/d' file.txt
Insertion
Insert text before line 3
sed '3i\New line above' file.txt
Append text after line 3
sed '3a\New line below' file.txt
Insert a header at the top of file
sed '1i\Header line' file.txt
Append a footer at end of file
sed '$a\Footer line' file.txt
In-Place Editing
Edit file in place on Linux
sed -i 's/old/new/g' file.txt
Edit file in place on macOS
sed -i '' 's/old/new/g' file.txt
Edit in place with backup
sed -i.bak 's/old/new/g' file.txt
Bulk edit multiple files
find . -name "*.txt" -exec sed -i 's/old/new/g' {} +
Advanced
Print only lines 5 through 10
sed -n '5,10p' file.txt
Print range between two patterns
sed -n '/start/,/end/p' file.txt
Transliterate characters a to A, b to B, c to C
sed 'y/abc/ABC/' file.txt
Multiple substitutions
sed -e 's/foo/bar/g' -e 's/baz/qux/g' file.txt
Quit after first match of pattern
sed '/pattern/q' file.txt
Quick Commands
Replace all occurrences of old with new
sed 's/old/new/g' file.txt
Edit a file in place with substitution
sed -i 's/old/new/g' file.txt
Print only lines 5 through 10
sed -n '5,10p' file.txt