Editing Streams with sed
How sed works line by line, the substitute command in depth (flags, delimiters, &, capture groups), editing files in place safely, addresses and ranges, deleting, printing, inserting and appending lines, and the sed one-liners used in scripts, Dockerfiles and CI pipelines.
What sed is
sed is a stream editor. Instead of opening a file in an editor and changing it by hand, you describe the change as a command, and sed applies it to every line:
How sed processes text
s/8080/9090/applied to every line it matches
(or written back with
-i)sed reads a line, runs the commands on it, prints it, and moves on. It never loads the whole file, so it works on huge files too.
Because no human is involved, sed is how automation changes text: shell scripts, Dockerfiles (RUN sed -i ...), CI pipelines, Ansible and cloud-init all use it. You'll also use it at the command line to clean up output.
sed [OPTIONS] 'SCRIPT' [FILE...]Always put the script in single quotes, so the shell leaves $, * and \ alone.
The substitute command: s
This is what you'll use most of the time:
Anatomy of a substitution
sed 's/8080/9090/' /etc/shopapp/app.conf | head -6# Shop application configuration
# Edit with care.
[server]
port=9090
host=0.0.0.0The changed text is printed; the file itself still says 8080. That makes sed safe to experiment with: nothing changes until you add -i.
Flags
| Flag | Effect |
|---|---|
| (none) | replace the first match on each line |
g | replace every match on the line |
2 | replace only the 2nd match on each line |
I | ignore case (GNU sed) |
p | print the line if a replacement was made (useful with -n) |
$ echo "aaa" | sed 's/a/b/'
baa
$ echo "aaa" | sed 's/a/b/g'
bbbAny delimiter
The character right after s is the delimiter. When the text contains slashes (paths, URLs), pick another one instead of escaping every /:
sed 's/\/usr\/local\/bin/\/opt\/bin/g' # hard to read
sed 's#/usr/local/bin#/opt/bin#g' # same thing, readable
sed 's|http://|https://|g' # | works tooThe pattern is a regex
The "find" part is a regular expression, exactly like in grep. So anchors and classes work, and special characters need escaping:
| Command | Effect |
|---|---|
s/^port=8080$/port=9090/ | only a line that is exactly port=8080 |
s/^host=.*/host=REDACTED/ | replace the whole value after host= (.* = the rest of the line) |
s/[0-9]\+/N/g | replace every number with N |
s/\s\+$// | remove trailing spaces at the end of lines |
s/\./,/g | replace literal dots (escaped) with commas |
& and capture groups in the replacement
In the replacement, & means "the whole matched text":
sed 's/^debug=true/#&/' app.conf # comment out a line: #debug=true
sed 's/[0-9]\+/[&]/g' # wrap every number in bracketsCapture groups remember parts of the match. With -E (extended regex), put parts in ( ) and refer to them as \1, \2, ...:
sed -E 's#([0-9]{2})/([0-9]{2})/([0-9]{4})#\3-\2-\1#' events.log| Part | Captures |
|---|---|
([0-9]{2}) | group 1: the day |
([0-9]{2}) | group 2: the month |
([0-9]{4}) | group 3: the year |
\3-\2-\1 | write them back as year-month-day |
2026-11-24 ERROR payment timeout
2026-11-24 INFO order placed
2026-11-25 WARN slow query24/11/2026 became 2026-11-24, the ISO format that sorts correctly.
Editing files in place: -i
-i writes the result back into the file instead of printing it.
| Command | Effect |
|---|---|
sed -i 's/a/b/' file | edit in place, no backup |
sed -i.bak 's/a/b/' file | edit in place, save the original as file.bak (no space after -i) |
sed -i.bak 's/^port=8080$/port=9090/' /etc/shopapp/app.conf
diff /etc/shopapp/app.conf.bak /etc/shopapp/app.conf5c5
< port=8080
---
> port=9090Exactly one line changed, and the original is in app.conf.bak.
The safe routine: preview without -i, check the output (or diff), then run again with -i.bak.
Redirecting into the same file: sed 's/a/b/' app.conf > app.conf. The shell empties app.conf before sed even starts reading it, so you end up with an empty file. Use -i, or write to a new file and mv it.
And on macOS, sed -i requires an argument (sed -i '' 's/a/b/' file), which is why scripts meant to run on both often use -i.bak.
Substitute and edit in place
Change the server port to 9090 directly in the file, keeping a backup.
The safe routine for changing a file with sed:
- Preview: run sed without
-i. It prints the result and doesn't touch the file. - Check that only the lines you wanted changed.
- Apply with
-i.bak: edit the file in place and keep the original asfile.bak.
1. Look at the config
cat -n /etc/shopapp/app.conf
grep port /etc/shopapp/app.confport=8080
port=5432Two port= lines: the web server's (8080) and the database's (5432). Only the first one should change.
2. Preview a substitution
sed 's/8080/9090/' /etc/shopapp/app.conf | head -6| Part | Meaning |
|---|---|
s | substitute |
/8080/ | find this |
9090/ | replace it with this |
/etc/shopapp/app.conf | the input file (it is not modified) |
# Shop application configuration
# Edit with care.
[server]
port=9090
host=0.0.0.0The output shows port=9090. The file itself still says 8080: check with grep port /etc/shopapp/app.conf.
3. Be precise
s/8080/9090/ would also change an 8080 anywhere else in the file, for example in a URL. Anchoring makes the intent exact: s/^port=8080$/port=9090/ only matches a line that is exactly port=8080.
4. Apply it, with a backup
sed -i.bak 's/^port=8080$/port=9090/' /etc/shopapp/app.conf
ls /etc/shopapp
diff /etc/shopapp/app.conf.bak /etc/shopapp/app.conf| Part | Meaning |
|---|---|
-i | edit the file in place |
.bak | (written right after -i, no space) save the original as app.conf.bak first |
app.conf
app.conf.bak
5c5
< port=8080
---
> port=9090The original is safe in app.conf.bak, and diff confirms that only line 5 changed.
Change the server port from 8080 to 9090 directly in /etc/shopapp/app.conf, keeping a backup of the original as /etc/shopapp/app.conf.bak. The database port must stay 5432.
Expected result: grep port /etc/shopapp/app.conf shows port=9090 and port=5432, and the .bak file still contains port=8080.
Hint: the commands, explained
sed -i.bak 's/^port=8080$/port=9090/' /etc/shopapp/app.confWhat each part does
sed -i.bak: edit the file in place, but first save the original asapp.conf.bak.s/^port=8080$/port=9090/: substitute.^start of line and$end of line, so only a line that is exactlyport=8080changes.
Replace everywhere
Turn every http:// link into https://, whatever its case.
Three details of s/// you'll need constantly:
| Detail | Example | Effect |
|---|---|---|
the g flag | s/a/b/g | replace every match on the line, not only the first |
the I flag | s/http/https/I | ignore upper and lower case (GNU sed) |
| another delimiter | s#http://#https://# | any character can replace /, which saves escaping slashes in paths and URLs |
1. First match versus every match
echo "aaa" | sed 's/a/b/'
echo "aaa" | sed 's/a/b/g'baa
bbbWithout g, sed stops after the first replacement on each line.
2. URLs: change the delimiter
With / as the delimiter, http:// would have to be written http:\/\/. Using # instead keeps it readable:
sed 's#http://#https://#g' /srv/site/links.html<a href="https://shop.example.com/">Home</a>
<a href="https://shop.example.com/cart">Cart</a>
<a href="https://docs.example.com/api">API docs</a>
<a href="HTTP://shop.example.com/help">Help</a>
<img src="https://cdn.example.com/logo.png">Four links fixed, but HTTP:// in capitals was missed.
3. Ignore case
sed 's#http://#https://#gI' /srv/site/links.htmlWhat I adds: the pattern matches http://, HTTP://, Http://, and so on.
<a href="https://shop.example.com/">Home</a>
<a href="https://shop.example.com/cart">Cart</a>
<a href="https://docs.example.com/api">API docs</a>
<a href="https://shop.example.com/help">Help</a>
<img src="https://cdn.example.com/logo.png">All five links now use https.
Edit /srv/site/links.html in place so that every http:// link, in any upper or lower case, becomes https://.
Expected result: grep -ci 'http://' /srv/site/links.html prints 0, and the file has 5 https:// links.
Hint: the commands, explained
sed -i 's#http://#https://#gI' /srv/site/links.htmlWhat each part does
s#http://#https://#gI:#is the separator (so the slashes in the URLs need no escaping).greplace every match on a line, not just the first;Iignore case, soHTTP://matches too.
Addresses: choosing which lines
By default, a command applies to every line. Put an address in front to limit it:
| Address | Lines |
|---|---|
5 | line 5 |
5,10 | lines 5 to 10 |
$ | the last line |
5,$ | line 5 to the end |
/regex/ | lines matching the regex |
/start/,/end/ | from a line matching start to the next line matching end |
/regex/! | lines not matching (! negates) |
The address goes right before the command: 5d, /^#/d, /\[database\]/,/^$/ s/.../.../.
Deleting lines: d
sed -e '/^#/d' -e '/^$/d' /etc/shopapp/app.conf| Part | Deletes |
|---|---|
/^#/d | lines starting with # (comments) |
/^$/d | empty lines |
-e | lets you give several commands |
[server]
port=9090
host=0.0.0.0
debug=true
[database]
host=db-old.internal
port=5432
name=shop
[cache]
host=cache-old.internal
ttl=300Only the settings. Other common deletions:
sed '1d' file.csv # delete the first line (a CSV header)
sed '$d' file # delete the last line
sed '/DEBUG/d' app.log # drop debug linesPrinting lines: p and -n
sed prints every line automatically. -n switches that off, and then p prints only what you select. Together, they make sed a precise line picker:
sed -n '5,7p' /etc/shopapp/app.conf
sed -n '/^\[database\]/,/^$/p' /etc/shopapp/app.conf
sed -n '$=' /etc/shopapp/app.conf| Command | Prints |
|---|---|
sed -n '5,7p' | lines 5 to 7 |
sed -n '/^\[database\]/,/^$/p' | the whole [database] section (\[ escapes the bracket) |
sed -n '$=' | the number of the last line: a line count |
port=9090
host=0.0.0.0
debug=true
[database]
host=db-old.internal
port=5432
name=shop
17sed -n '/ERROR/p' is the same as grep ERROR, but ranges like /start/,/end/ are something grep can't do: "show me the log from the first 'deploy started' to 'deploy finished'".
Delete and print lines
Produce a clean copy of the config without comments or blank lines.
Besides substituting, sed can delete lines (d) and print lines (p). Both take an address in front that says which lines:
| Address | Selects |
|---|---|
5 | line 5 |
5,7 | lines 5 to 7 |
$ | the last line |
/pattern/ | every line matching the regex |
/start/,/end/ | from a line matching start to the next line matching end |
sed -n turns off the automatic printing, so only lines you explicitly print appear.
1. Print lines by number or range
sed -n '5,7p' /etc/shopapp/app.conf
sed -n '/^\[database\]/,/^$/p' /etc/shopapp/app.conf| Command | Prints |
|---|---|
sed -n '5,7p' | lines 5 to 7 only, like head -7 | tail -3 |
sed -n '/^\[database\]/,/^$/p' | from the [database] line to the next empty line: the whole section. \[ escapes the bracket, which is special in regex. |
port=9090
host=0.0.0.0
debug=true
[database]
host=db-old.internal
port=5432
name=shop
2. Delete lines
sed '/^#/d' /etc/shopapp/app.conf
sed -e '/^#/d' -e '/^$/d' /etc/shopapp/app.conf| Part | Meaning |
|---|---|
/^#/d | delete lines that start with # (comments) |
/^$/d | delete empty lines (start and end with nothing in between) |
-e ... -e ... | several commands in one run |
[server]
port=9090
host=0.0.0.0
debug=true
[database]
host=db-old.internal
port=5432
name=shop
[cache]
host=cache-old.internal
ttl=300Only the settings remain: 11 lines instead of 17. The file itself is unchanged, because there's no -i.
Save a copy of /etc/shopapp/app.conf without comment lines and without empty lines to /root/app-clean.conf. Don't change the original.
Expected result: /root/app-clean.conf has 11 lines, none starting with #, none empty, and app.conf still has its comments.
Hint: the commands, explained
sed -e '/^#/d' -e '/^$/d' /etc/shopapp/app.conf > /root/app-clean.confWhat each part does
-egives sed several commands in one run./^#/d: delete lines starting with#(comments)./^$/d: delete empty lines (start immediately followed by end).- No
-i, so the original is untouched; the cleaned output goes to a new file with>.
Limiting a substitution to a range
Ranges really shine in front of s. When the same key appears in several sections, change only one:
sed '/^\[database\]/,/^$/ s/^host=.*/host=db-new.internal/' /etc/shopapp/app.conf | grep hosthost=0.0.0.0
host=db-new.internal
host=cache-old.internalOnly the host inside [database] changed; the server and cache hosts are untouched.
Inserting, appending and changing lines
| Command | Effect |
|---|---|
/regex/a TEXT | append a line after each matching line |
/regex/i TEXT | insert a line before |
/regex/c TEXT | change: replace the whole line |
3i TEXT | insert before line 3 |
$a TEXT | append at the end of the file |
sed '/^\[database\]/a timeout=30' /etc/shopapp/app.conf | sed -n '10,14p'[database]
timeout=30
host=db-old.internal
port=5432
name=shopA new setting right under the section header.
sed '/^\[cache\]/i # Cache settings' app.conf # add a comment above [cache]
sed '$a export PATH=$PATH:/opt/app/bin' ~/.bashrc # add a line at the end
sed '/^port=/c port=9090' app.conf # replace the whole port lineTargeted changes
Point only the database section at the new host, and switch debug mode off.
Config files often repeat the same key in several sections: here, host= appears under [server], [database] and [cache]. A plain s/^host=.*/.../ would change all three. Put an address range in front of the s command and it only applies inside that range:
sed '/^\[database\]/,/^$/ s/^host=.*/host=db-new.internal/' app.confreads: "from the [database] line to the next empty line, replace the host".
1. The problem with a global replacement
sed 's/^host=.*/host=REDACTED/' /etc/shopapp/app.conf | grep host.* means "anything to the end of the line", so this replaces the whole value.
host=REDACTED
host=REDACTED
host=REDACTEDAll three hosts changed. Fine for redacting, wrong for a migration.
2. Limit it to one section
sed '/^\[database\]/,/^$/ s/^host=.*/host=db-new.internal/' /etc/shopapp/app.conf | grep host| Part | Meaning |
|---|---|
/^\[database\]/,/^$/ | the address range: from the [database] header to the next empty line |
s/^host=.*/host=db-new.internal/ | the substitution, applied only inside that range |
host=0.0.0.0
host=db-new.internal
host=cache-old.internalOnly the database host changed.
3. Comment a line out
Turning a setting off by commenting it out keeps it visible for later. & in the replacement means "the whole text that matched":
sed 's/^debug=true/#&/' /etc/shopapp/app.conf | grep debug#debug=trueEdit /etc/shopapp/app.conf in place so that:
- the database section's host becomes
db-new.internal(the server and cache hosts stay as they are), and - the line
debug=trueis commented out as#debug=true.
Expected result: grep host /etc/shopapp/app.conf shows 0.0.0.0, db-new.internal and cache-old.internal, and grep debug shows #debug=true.
Hint: the commands, explained
sed -i -e '/^\[database\]/,/^$/ s/^host=.*/host=db-new.internal/' -e 's/^debug=true/#&/' /etc/shopapp/app.confWhat each part does
/^\[database\]/,/^$/ s/.../.../: a range: from the line[database]to the next empty line, and the substitution runs only there.\[matches a literal bracket.s/^host=.*/host=db-new.internal/: replace the wholehost=line inside that section.s/^debug=true/#&/:&means "what was matched", so the line becomes#debug=true, commented out.
Other useful bits
| Command | Effect |
|---|---|
sed '2q' | print up to line 2, then quit (like head -2, and stops reading early) |
sed -n '/regex/{p;q}' | print the first match and stop |
sed 's/\r$//' | remove Windows carriage returns |
sed -E | extended regex: +, ?, {n}, ( ), | without backslashes |
sed -i -e '...' -e '...' | several edits in one pass |
sed in real DevOps work
# Dockerfile: point apt at a local mirror
RUN sed -i 's#http://archive.ubuntu.com#http://mirror.internal#g' /etc/apt/sources.list
# Set a version in a Kubernetes manifest during CI
sed -i "s#image: shop:.*#image: shop:${GIT_SHA}#" deployment.yaml
# Disable password logins for SSH
sed -i 's/^#\?PasswordAuthentication .*/PasswordAuthentication no/' /etc/ssh/sshd_config
# Show the part of a log between two markers
sed -n '/deploy started/,/deploy finished/p' deploy.logNote the double quotes in the CI example: they let the shell fill in ${GIT_SHA}. Use double quotes when you need variables, single quotes otherwise.
After changing a config file with sed, validate it before reloading the service: nginx -t, sshd -t, visudo -c, python3 -m json.tool file.json. A sed command that matches more than you expected can break a service.
"How do you replace a string in a file from the command line?" sed -i 's/old/new/g' file, ideally with -i.bak to keep a backup, and a preview first without -i.
"How do you delete blank lines or comments?" sed '/^$/d' and sed '/^#/d', or both: sed -e '/^#/d' -e '/^$/d'.
"How do you print lines 10 to 20 of a file?" sed -n '10,20p' file.
"When would you use sed instead of awk?" sed for substitutions and line-based edits; awk when you need to work with columns, calculations or conditions.
Summary
- sed applies commands to each line and prints the result; the file is unchanged unless you use
-i(use-i.bakfor a backup). s/find/replace/flags:gevery match,Iignore case, any delimiter (s#a#b#),&the match,\1capture groups with-E.- Addresses:
N,N,M,$,/regex/,/start/,/end/,!to negate. - Commands:
ddelete,pprint (with-n),aappend,iinsert,cchange,qquit. - Preview, then
-i.bak, then validate the config before reloading the service.
Quick quiz
You've practised everything in this lesson
Every task was checked on your own machine. You can end the lab, or keep experimenting in the terminal.