What is sed?
sed (Stream Editor) is a non-interactive text editor that processes input line by line. It is ideal for automated text transformations, search-and-replace operations, and scripted file modifications on your Breeze.
Basic Syntax
sed [options] 'command' filename
Search and Replace
# Replace first occurrence per line
sed 's/old/new/' file.txt
# Replace ALL occurrences per line (global flag)
sed 's/old/new/g' file.txt
# Case-insensitive replacement
sed 's/error/warning/Ig' logfile.txt
# Edit file in place
sed -i 's/old/new/g' config.conf
# Create a backup before in-place editing
sed -i.bak 's/old/new/g' config.conf
Deleting Lines
# Delete line 5
sed '5d' file.txt
# Delete lines 10 through 20
sed '10,20d' file.txt
# Delete blank lines
sed '/^$/d' file.txt
# Delete lines matching a pattern
sed '/^#/d' config.conf # Remove comments
sed '/DEBUG/d' app.log # Remove debug lines
Inserting and Appending
# Insert a line before line 3
sed '3i\New line inserted here' file.txt
# Append a line after line 5
sed '5a\Appended after line 5' file.txt
# Insert before a matching pattern
sed '/\[mysqld\]/i\# Custom MySQL settings' my.cnf
Printing Specific Lines
# Print only line 10
sed -n '10p' file.txt
# Print lines 5 through 15
sed -n '5,15p' file.txt
# Print lines matching a pattern
sed -n '/error/p' logfile.txt
# Print lines between two patterns
sed -n '/START/,/END/p' file.txt
Using Regular Expressions
# Extended regex with -E
sed -E 's/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/REDACTED/g' access.log
# Capture groups
sed -E 's/^([a-z]+):([0-9]+)/User: \1, Port: \2/' data.txt
# Remove HTML tags
sed -E 's/]+>//g' page.html
Multiple Commands
# Using -e flag
sed -e 's/foo/bar/g' -e 's/baz/qux/g' file.txt
# Using semicolons
sed 's/foo/bar/g; s/baz/qux/g' file.txt
# Using a sed script file
sed -f commands.sed file.txt
Practical Server Examples
# Update a config value
sed -i 's/^listen_port=.*/listen_port=8080/' app.conf
# Comment out a line
sed -i 's/^dangerous_setting/#&/' config.conf
# Uncomment a line
sed -i 's/^#\(wanted_setting\)/\1/' config.conf
# Remove trailing whitespace
sed -i 's/[[:space:]]*$//' script.sh
# Add a line after a match (e.g., add a server block entry)
sed -i '/^upstream backend/a\ server 10.0.0.5:8080;' nginx.conf
Important Notes
- Always test without
-ifirst to preview changes - Use
-i.bakto create backups when editing in place - On macOS/BSD,
sed -irequires an explicit backup extension:sed -i '' 's/old/new/g' - Combine
sedwithfindfor bulk operations:find . -name "*.conf" -exec sed -i 's/old/new/g' {} +