sed
15 commands
15 shown
Substitute first match per line
Replace the first occurrence of 'foo' with 'bar' per line
sed 's/foo/bar/' file.txt
Substitute all matches (global)
Replace every occurrence per line with the /g flag
sed 's/foo/bar/g' file.txt
In-place edit
Modify file in-place (no backup); on macOS add empty string: -i ''
sed -i 's/old/new/g' config.cfg
In-place edit with backup
Edit in-place and save original as file.txt.bak
sed -i.bak 's/old/new/g' file.txt
Delete matching lines
Delete all comment lines starting with #
sed '/^#/d' config.txt
Delete blank lines
Remove all empty or whitespace-only lines
sed '/^[[:space:]]*$/d' file.txt
Print specific line numbers
Print lines 10 through 20 only (suppress default output with -n)
sed -n '10,20p' file.txt
Print lines matching pattern
Print only lines that match ERROR
sed -n '/ERROR/p' app.log
Insert line before match
Insert a comment line before every server_name directive
sed '/^server_name/i # Added by deploy script' nginx.conf
Append line after match
Append a setting line after the [defaults] header
sed '/^\[defaults\]/a ansible_python_interpreter=/usr/bin/python3' ansible.cfg
Case-insensitive substitution
GNU sed /I flag for case-insensitive match
sed 's/error/ERROR/gI' file.txt
Multiple expressions
Apply multiple substitutions in one command
sed -e 's/foo/bar/g' -e 's/baz/qux/g' file.txt
Strip leading/trailing whitespace
Trim leading and trailing whitespace from each line
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' file.txt
Address range substitution
Apply substitution only to lines 5 through 15
sed '5,15s/DEBUG/INFO/g' app.log
Extract value from key=value file
Print the value of DB_HOST from a .env file
sed -n 's/^DB_HOST=//p' .env
no commands match