Learn / Linux / Text Processing
Lesson 13 of 74

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.

25 min read Report a problem Hands-on lab included 6-question quiz

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

Inputa file, or a pipe
one line at a time
sed scripte.g. s/8080/9090/
applied to every line it matches
Outputprinted to the screen
(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.

text
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

ssubstitute
/delimiter
http://what to find (a regex)
/
https://what to put instead
/
gIflags: every match, ignore case
bash
sed 's/8080/9090/' /etc/shopapp/app.conf | head -6
text
# Shop application configuration
# Edit with care.

[server]
port=9090
host=0.0.0.0

The changed text is printed; the file itself still says 8080. That makes sed safe to experiment with: nothing changes until you add -i.

Flags

FlagEffect
(none)replace the first match on each line
greplace every match on the line
2replace only the 2nd match on each line
Iignore case (GNU sed)
pprint the line if a replacement was made (useful with -n)
text
$ echo "aaa" | sed 's/a/b/'
baa
$ echo "aaa" | sed 's/a/b/g'
bbb

Any delimiter

The character right after s is the delimiter. When the text contains slashes (paths, URLs), pick another one instead of escaping every /:

text
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 too

The 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:

CommandEffect
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/greplace every number with N
s/\s\+$//remove trailing spaces at the end of lines
s/\./,/greplace literal dots (escaped) with commas

& and capture groups in the replacement

In the replacement, & means "the whole matched text":

text
sed 's/^debug=true/#&/' app.conf          # comment out a line: #debug=true
sed 's/[0-9]\+/[&]/g'                     # wrap every number in brackets

Capture groups remember parts of the match. With -E (extended regex), put parts in ( ) and refer to them as \1, \2, ...:

bash
sed -E 's#([0-9]{2})/([0-9]{2})/([0-9]{4})#\3-\2-\1#' events.log
PartCaptures
([0-9]{2})group 1: the day
([0-9]{2})group 2: the month
([0-9]{4})group 3: the year
\3-\2-\1write them back as year-month-day
text
2026-11-24 ERROR payment timeout
2026-11-24 INFO order placed
2026-11-25 WARN slow query

24/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.

CommandEffect
sed -i 's/a/b/' fileedit in place, no backup
sed -i.bak 's/a/b/' fileedit in place, save the original as file.bak (no space after -i)
bash
sed -i.bak 's/^port=8080$/port=9090/' /etc/shopapp/app.conf
diff /etc/shopapp/app.conf.bak /etc/shopapp/app.conf
text
5c5
< port=8080
---
> port=9090

Exactly 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.

Try it · Task 1 of 4

Substitute and edit in place

Change the server port to 9090 directly in the file, keeping a backup.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

The safe routine for changing a file with sed:

  1. Preview: run sed without -i. It prints the result and doesn't touch the file.
  2. Check that only the lines you wanted changed.
  3. Apply with -i.bak: edit the file in place and keep the original as file.bak.

1. Look at the config

bash
cat -n /etc/shopapp/app.conf
grep port /etc/shopapp/app.conf
text
port=8080
port=5432

Two port= lines: the web server's (8080) and the database's (5432). Only the first one should change.

2. Preview a substitution

bash
sed 's/8080/9090/' /etc/shopapp/app.conf | head -6
PartMeaning
ssubstitute
/8080/find this
9090/replace it with this
/etc/shopapp/app.confthe input file (it is not modified)
text
# Shop application configuration
# Edit with care.

[server]
port=9090
host=0.0.0.0

The 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

bash
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
PartMeaning
-iedit the file in place
.bak(written right after -i, no space) save the original as app.conf.bak first
text
app.conf
app.conf.bak
5c5
< port=8080
---
> port=9090

The original is safe in app.conf.bak, and diff confirms that only line 5 changed.

2 · Your task

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
text
sed -i.bak 's/^port=8080$/port=9090/' /etc/shopapp/app.conf

What each part does

  • sed -i.bak: edit the file in place, but first save the original as app.conf.bak.
  • s/^port=8080$/port=9090/: substitute. ^ start of line and $ end of line, so only a line that is exactly port=8080 changes.
First start the lab machine in the terminal panel on the right.
Try it · Task 2 of 4

Replace everywhere

Turn every http:// link into https://, whatever its case.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

Three details of s/// you'll need constantly:

DetailExampleEffect
the g flags/a/b/greplace every match on the line, not only the first
the I flags/http/https/Iignore upper and lower case (GNU sed)
another delimiters#http://#https://#any character can replace /, which saves escaping slashes in paths and URLs

1. First match versus every match

bash
echo "aaa" | sed 's/a/b/'
echo "aaa" | sed 's/a/b/g'
text
baa
bbb

Without 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:

bash
sed 's#http://#https://#g' /srv/site/links.html
text
<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

bash
sed 's#http://#https://#gI' /srv/site/links.html

What I adds: the pattern matches http://, HTTP://, Http://, and so on.

text
<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.

2 · Your task

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
text
sed -i 's#http://#https://#gI' /srv/site/links.html

What each part does

  • s#http://#https://#gI: # is the separator (so the slashes in the URLs need no escaping). g replace every match on a line, not just the first; I ignore case, so HTTP:// matches too.
First start the lab machine in the terminal panel on the right.

Addresses: choosing which lines

By default, a command applies to every line. Put an address in front to limit it:

AddressLines
5line 5
5,10lines 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

bash
sed -e '/^#/d' -e '/^$/d' /etc/shopapp/app.conf
PartDeletes
/^#/dlines starting with # (comments)
/^$/dempty lines
-elets you give several commands
text
[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=300

Only the settings. Other common deletions:

text
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 lines

Printing 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:

bash
sed -n '5,7p' /etc/shopapp/app.conf
sed -n '/^\[database\]/,/^$/p' /etc/shopapp/app.conf
sed -n '$=' /etc/shopapp/app.conf
CommandPrints
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
text
port=9090
host=0.0.0.0
debug=true
[database]
host=db-old.internal
port=5432
name=shop

17

sed -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'".

Try it · Task 3 of 4

Delete and print lines

Produce a clean copy of the config without comments or blank lines.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

Besides substituting, sed can delete lines (d) and print lines (p). Both take an address in front that says which lines:

AddressSelects
5line 5
5,7lines 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

bash
sed -n '5,7p' /etc/shopapp/app.conf
sed -n '/^\[database\]/,/^$/p' /etc/shopapp/app.conf
CommandPrints
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.
text
port=9090
host=0.0.0.0
debug=true
[database]
host=db-old.internal
port=5432
name=shop

2. Delete lines

bash
sed '/^#/d' /etc/shopapp/app.conf
sed -e '/^#/d' -e '/^$/d' /etc/shopapp/app.conf
PartMeaning
/^#/ddelete lines that start with # (comments)
/^$/ddelete empty lines (start and end with nothing in between)
-e ... -e ...several commands in one run
text
[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=300

Only the settings remain: 11 lines instead of 17. The file itself is unchanged, because there's no -i.

2 · Your task

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
text
sed -e '/^#/d' -e '/^$/d' /etc/shopapp/app.conf > /root/app-clean.conf

What each part does

  • -e gives 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 >.
First start the lab machine in the terminal panel on the right.

Limiting a substitution to a range

Ranges really shine in front of s. When the same key appears in several sections, change only one:

bash
sed '/^\[database\]/,/^$/ s/^host=.*/host=db-new.internal/' /etc/shopapp/app.conf | grep host
text
host=0.0.0.0
host=db-new.internal
host=cache-old.internal

Only the host inside [database] changed; the server and cache hosts are untouched.

Inserting, appending and changing lines

CommandEffect
/regex/a TEXTappend a line after each matching line
/regex/i TEXTinsert a line before
/regex/c TEXTchange: replace the whole line
3i TEXTinsert before line 3
$a TEXTappend at the end of the file
bash
sed '/^\[database\]/a timeout=30' /etc/shopapp/app.conf | sed -n '10,14p'
text
[database]
timeout=30
host=db-old.internal
port=5432
name=shop

A new setting right under the section header.

text
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 line
Try it · Task 4 of 4

Targeted changes

Point only the database section at the new host, and switch debug mode off.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

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:

text
sed '/^\[database\]/,/^$/ s/^host=.*/host=db-new.internal/' app.conf

reads: "from the [database] line to the next empty line, replace the host".

1. The problem with a global replacement

bash
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.

text
host=REDACTED
host=REDACTED
host=REDACTED

All three hosts changed. Fine for redacting, wrong for a migration.

2. Limit it to one section

bash
sed '/^\[database\]/,/^$/ s/^host=.*/host=db-new.internal/' /etc/shopapp/app.conf | grep host
PartMeaning
/^\[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
text
host=0.0.0.0
host=db-new.internal
host=cache-old.internal

Only 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":

text
sed 's/^debug=true/#&/' /etc/shopapp/app.conf | grep debug
text
#debug=true
2 · Your task

Edit /etc/shopapp/app.conf in place so that:

  1. the database section's host becomes db-new.internal (the server and cache hosts stay as they are), and
  2. the line debug=true is 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
text
sed -i -e '/^\[database\]/,/^$/ s/^host=.*/host=db-new.internal/' -e 's/^debug=true/#&/' /etc/shopapp/app.conf

What 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 whole host= line inside that section.
  • s/^debug=true/#&/: & means "what was matched", so the line becomes #debug=true, commented out.
First start the lab machine in the terminal panel on the right.

Other useful bits

CommandEffect
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 -Eextended regex: +, ?, {n}, ( ), | without backslashes
sed -i -e '...' -e '...'several edits in one pass

sed in real DevOps work

text
# 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.log

Note 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.bak for a backup).
  • s/find/replace/flags: g every match, I ignore case, any delimiter (s#a#b#), & the match, \1 capture groups with -E.
  • Addresses: N, N,M, $, /regex/, /start/,/end/, ! to negate.
  • Commands: d delete, p print (with -n), a append, i insert, c change, q quit.
  • Preview, then -i.bak, then validate the config before reloading the service.
Check your understanding

Quick quiz

Feedback