# Syntaxsed [options] command [input-file]# With pipelinecat report.txt | sed 's/Nick/John/g'
Search for text
# Search for a stringsed -n '/hello/p' file.txt# Case insensitive searchsed -n '/hello/Ip' file.txt# Only output lines that do not matchsed -n '/hello/!p' file.txt
Change lines
# Insert text before line 5sed '5i line number five' file.txt# Insert before lines with "hello"$ sed '/hello/i Example: ' file.txt# Delete line 5-7 in filesed '5,7d' file.txt
Option Example
Option
Example
Description
-i
sed -ibak 's/On/Off/' php.ini
Backup and modify input file directly
-E
sed -E 's/[0-9]+//g' input-file
Use extended regular expressions
-n
sed -n '3 p' config.conf
Suppress default pattern space printing
-f
sed -f script.sed config.conf
Execute sed script file
-e
sed -e 'command1' -e 'command2' input-file
Execute multiple sed commands
Commands
Command
Example
Description
p
sed -n '1,4 p' input.txt
Print lines 1-4
d
sed '1,4 d' input.txt
Print lines except 1-4
w
sed -n '1,4 w output.txt' input.txt
Write pattern space to file
a
sed '2 a new-line' input.txt
Append line after
i
sed '2 i new-line' input.txt
Insert line before
Sed substitute command and flags
shell
sed 's/original-string/replacement-string/[flags]' [input-file]
Flag
Description
Example
g
Global substitution
sed 's/development/production/g' .env
1,2...
Substitute the nth occurrence
sed 's/latin1/utf8/2' locale.sql
p
Print only the substituted line
sed -n 's/error_log = 0/error_log = 1/p' php.ini
w
Write only the substituted line to a file
sed -n 's/One/Two/w output.txt' words.txt
i
Ignore case while searching
sed 's/true/FALSE/i' config.php
e
Substitute and execute in the command line
sed 's/^/ls -l /e' files.list
&
Gets the matched pattern
sed 's/^.*/<&>/' index.xml
( ) \1 \2 \3
Group using ( and ). Use \1, \2 in replacement to refer the group
sed 's/([^,]*),([^,]*),([^,]*).*/\1,\3/g' words.txt