sed command snippets

Copy-paste-ready sed commands for find-replace, line deletion, text extraction, and config editing.

sed command snippets

Copy-paste-ready sed commands for find-replace, line deletion, text extraction, and config editing.

Replace All Occurrences of a String in a File with sed

sed substitutes every match on every line:

sed -i 's/old_text/new_text/g' file.txt

Delete Blank Lines from a File with sed

sed removes all empty lines:

sed -i '/^$/d' file.txt

sed extracts lines 10 through 20:

sed -n '10,20p' file.txt

Delete Lines Matching a Pattern with sed

sed removes all lines containing "DEBUG":

sed -i '/DEBUG/d' application.log

Insert a Line Before a Match with sed

sed inserts text before the line containing "[mysqld]":

sed -i '/\[mysqld\]/i max_connections = 200' /etc/mysql/my.cnf

Append a Line After a Match with sed

sed appends text after the line containing "[mysqld]":

sed -i '/\[mysqld\]/a innodb_buffer_pool_size = 1G' /etc/mysql/my.cnf

Replace Text Only on Lines Matching a Pattern with sed

sed substitutes only on lines that also match a filter pattern:

sed -i '/server_name/s/old_domain/new_domain/g' /etc/nginx/nginx.conf

Remove Comment Lines from a Config File with sed

sed strips lines starting with # and blank lines in one pass:

sed '/^#/d; /^$/d' config.conf