sed find and replace in a stream
sed (stream editor) applies editing commands to each line of its input. Its most common use is find and replace with s/old/new/, but it can also delete lines, print a range of lines, or edit files in place.
Availability Preinstalled on macOS, Linux and BSD
Syntax
sed [options] 'command' [file ...]
Common options
| Option | What it does |
|---|---|
s/old/new/ | Replace the first match on each line |
s/old/new/g | Replace every match on each line |
-n '10,20p' | Print only lines 10 to 20 |
'/pattern/d' | Delete lines that match |
-E | Use extended regular expressions |
-i.bak | Edit the file in place and keep a .bak backup (works on GNU and macOS) |
Examples
Replace text everywhere
sed 's/http:/https:/g' urls.txt
Print a range of lines
sed -n '10,20p' app.log
Delete comment lines
sed '/^#/d' config.txt
Edit a file in place with a backup
sed -i.bak 's/staging/production/g' settings.env
Use sed with sqx
Clean a URL list before auditing it
Drop comments and blank lines, then check every URL.
sed -e '/^#/d' -e '/^$/d' urls.txt | sqx -i lines "SELECT url, http_status(url) AS status FROM stdin"
Use a semicolon-separated export
Some spreadsheet exports use ; between fields. Swap it for a comma when no field contains commas or semicolons.
sed 's/;/,/g' export.csv | sqx "SELECT * FROM stdin LIMIT 5"
On macOS, sed -i needs a backup suffix argument: use -i.bak, or -i '' for no backup. GNU sed accepts plain -i.
Full documentation
This page covers the essentials. For every option, see the official documentation:
Or read the manual in your terminal: man sed