Skip to content
Laviyx Learn

Try

Linux and Bash course menu

Linux sed Command with Examples: Find and Replace

Use sed to find and replace text, change files in place with -i, delete and print lines, target line ranges, and use regular expressions with groups.

Intermediate5 min readUpdated
On this page

sed (stream editor) edits text line by line without opening an editor. It is often used in scripts to change configuration files.

Terminal
cat app.conf
Output
# Server settings
host=localhost
port=8080

debug=true
# Database
db_host=localhost
db_port=5432

Find and replace#

The form is s/old/new/:

Terminal
sed 's/localhost/10.0.0.5/' app.conf | head -n 3
Output
# Server settings
host=10.0.0.5
port=8080

By default, sed prints the result and does not change the file. It replaces only the first match on each line; add g for all matches:

Terminal
echo "cat cat cat" | sed 's/cat/dog/'
echo "cat cat cat" | sed 's/cat/dog/g'
echo "Cat CAT" | sed 's/cat/dog/gi'
Output
dog cat cat
dog dog dog
dog dog

i ignores case. If your text contains slashes, use another separator:

Terminal
echo "/usr/local/bin" | sed 's#/usr/local#/opt#'
Output
/opt/bin

Edit a file in place#

-i changes the file. -i.bak keeps a backup first:

Terminal
sed -i.bak 's/port=8080/port=9090/' app.conf
grep -n '^port' app.conf app.conf.bak
Output
app.conf:3:port=9090
app.conf.bak:3:port=8080

Delete and print lines#

d deletes matching lines. Here we remove comments and empty lines, which is a handy way to read a config file:

Terminal
sed '/^#/d; /^$/d' app.conf
Output
host=localhost
port=9090
debug=true
db_host=localhost
db_port=5432

-n turns off normal printing, and p prints chosen lines:

Terminal
sed -n '2,3p' app.conf
sed -n '/^db/p' app.conf
Output
host=localhost
port=9090
db_host=localhost
db_port=5432

Target particular lines#

Put an address before a command:

AddressApplies to
3Line 3
2,4Lines 2 to 4
$The last line
/debug/Lines matching a pattern
Terminal
sed '5s/true/false/' app.conf | sed -n '5p'
sed '/debug/s/true/false/' app.conf | grep debug
Output
debug=false
debug=false

Insert lines#

i inserts before, and a appends after:

Terminal
sed '/^port/a timeout=30' app.conf | sed -n '2,4p'
Output
host=localhost
port=9090
timeout=30

Groups#

With -E, parentheses capture text, and \1 and \2 reuse it. This swaps the name and value:

Terminal
echo "host=localhost" | sed -E 's/(.+)=(.+)/\2 is the \1/'
echo "2026-11-05" | sed -E 's/([0-9]+)-([0-9]+)-([0-9]+)/\3\/\2\/\1/'
Output
localhost is the host
05/11/2026

Common mistakes#

Practice#

Practice exercise

Without changing the file, print app.conf with comments removed and every localhost replaced by db.local.

Show solution
Terminal
sed '/^#/d; s/localhost/db.local/g' app.conf
Output
host=db.local
port=9090

debug=true
db_host=db.local
db_port=5432

Key takeaway#

Next: Working with Columns in awk.

Finished this lesson?