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.
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.
cat app.conf# Server settings
host=localhost
port=8080
debug=true
# Database
db_host=localhost
db_port=5432Find and replace#
The form is s/old/new/:
sed 's/localhost/10.0.0.5/' app.conf | head -n 3# Server settings
host=10.0.0.5
port=8080By 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:
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'dog cat cat
dog dog dog
dog dogi ignores case. If your text contains slashes, use another separator:
echo "/usr/local/bin" | sed 's#/usr/local#/opt#'/opt/binEdit a file in place#
-i changes the file. -i.bak keeps a backup first:
sed -i.bak 's/port=8080/port=9090/' app.conf
grep -n '^port' app.conf app.conf.bakapp.conf:3:port=9090
app.conf.bak:3:port=8080Delete and print lines#
d deletes matching lines. Here we remove comments and empty lines, which is a handy way to read a config file:
sed '/^#/d; /^$/d' app.confhost=localhost
port=9090
debug=true
db_host=localhost
db_port=5432-n turns off normal printing, and p prints chosen lines:
sed -n '2,3p' app.conf
sed -n '/^db/p' app.confhost=localhost
port=9090
db_host=localhost
db_port=5432Target particular lines#
Put an address before a command:
sed '5s/true/false/' app.conf | sed -n '5p'
sed '/debug/s/true/false/' app.conf | grep debugdebug=false
debug=falseInsert lines#
i inserts before, and a appends after:
sed '/^port/a timeout=30' app.conf | sed -n '2,4p'host=localhost
port=9090
timeout=30Groups#
With -E, parentheses capture text, and \1 and \2 reuse it. This swaps the name and value:
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/'localhost is the host
05/11/2026Common mistakes#
Practice#
Practice exercise
Without changing the file, print app.conf with comments removed and every localhost replaced by db.local.
Show solution
sed '/^#/d; s/localhost/db.local/g' app.confhost=db.local
port=9090
debug=true
db_host=db.local
db_port=5432Key takeaway#
Next: Working with Columns in awk.
Finished this lesson?