Substitution patterns
Replace first match per line
sed "s/foo/bar/" input.txt
Example:
sed "s/localhost/127.0.0.1/g" .env
Use regex capture groups
sed -E "s/(v)([0-9]+)/\1-\2/" tags.txt
Example:
sed -E "s#https?://##" urls.txt
In-place editing
Edit file in place (GNU sed)
sed -i "s/debug=false/debug=true/" app.conf
Example:
sed -i.bak "s/8080/9090/" app.conf
Delete lines matching pattern
sed -i "/^#/d" .env
Example:
sed "/ERROR/d" app.log
Line selection and printing
Print line ranges
sed -n "1,20p" server.log
Example:
sed -n "/BEGIN/,/END/p" output.txt
Print matching lines only
sed -n "/timeout/p" app.log
Example:
sed -n "5p" file.txt
Common mistakes / Pitfalls
- macOS and GNU sed differ for -i syntax; test before scripting.
- Unescaped slashes in replacement text can break substitution commands.
- In-place edits without backup can permanently damage important files.
Last updated: February 2026