Substitution
Basic substitution — replace first occurrence per line
echo 'hello world hello' | sed 's/hello/goodbye/'
Global substitution — replace all occurrences per line
echo 'hello world hello' | sed 's/hello/goodbye/g'
Replace nth occurrence — third match only
echo 'a:b:c:d:e' | sed 's/:/-/3'
Alternate delimiter — useful when pattern contains slashes
echo '/usr/local/bin' | sed 's|/usr/local|/opt|'
Case-insensitive substitution (GNU sed)
echo 'Hello HELLO hello' | sed 's/hello/goodbye/Ig'
Backreference swap — reverse two captured groups
cat <<'EOF' > /tmp/names.txt
Modestus, Evan
Smith, John
Garcia, Maria
EOF
sed 's/\([^,]*\), \(.*\)/\2 \1/' /tmp/names.txt
Delete lines matching a pattern
cat <<'EOF' > /tmp/config.txt
# This is a comment
server=10.50.1.20
# Another comment
port=443
timeout=30
EOF
sed '/^#/d' /tmp/config.txt
Strip trailing whitespace from every line
printf 'hello \nworld \n' | sed 's/[[:space:]]*$//'
Replace only on lines matching a condition
cat <<'EOF' > /tmp/hosts.txt
10.50.1.20 ise-01 active
10.50.1.50 ad-dc standby
10.50.1.1 pfsense active
EOF
sed '/standby/s/ad-dc/ad-dc-backup/' /tmp/hosts.txt
Chain multiple substitutions with -e
echo 'foo bar baz' | sed -e 's/foo/FOO/' -e 's/baz/BAZ/'