Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

sed: replace, delete and insert text

By updated

Improve this page

A port to change in a configuration, comments to strip before handing a file to a program: sed does these jobs in one command, without opening an editor. It reads a text line by line, applies the commands you give it to each line, and writes the result to standard output. The original file only changes if you ask for it with -i.

The lesson Search and replace in a file has already shown s, -i and .bak. This page adds what it does not cover: the read cycle, addresses and their silent pitfalls, and editing a file with a way back.

What you will learn

  • Predict what sed prints and what becomes of the file, with or without -n and -i
  • Replace text with s and check that the replacement happened
  • Choose the lines that are touched: number, pattern, range between two patterns, negation
  • Reuse the matched text with & and groups, and add a line
  • Edit a file with -i without overwriting its backup, then roll back
  • Recognise the cases where jq, yq, awk or Ansible are a better fit than sed

Prerequisites

You know how to use redirections and pipes, compare two files with diff (the 3c3 format, exit code 1 when they differ), and you have read Regular expression basics: the ^ and $ anchors, classes, basic and extended regular expressions (-E). The sed script is written between single quotes, so that the shell does not interpret $, * or \.

Create the practice folder

Type these commands as they are: they create four files and a symbolic link in ~/sed-lab. The commands of the lesson are run from this folder.

Terminal window
mkdir -p ~/sed-lab && cd ~/sed-lab
export LC_ALL=C.UTF-8
printf '%s\n' '# configuration' 'host=serveur serveur' 'port=8080' '[db]' 'user=admin' 'port=5432' '[web]' 'port=80' 'date=2026-11-24' '[cache]' 'debug=false' > config.conf
printf '%s\n' '# serveur' 'host=localhost' 'port=8080' > app.conf
printf '%s\n' '/usr/local/bin/app' '/etc/app/app.conf' '/var/log/app.log' > paths.txt
printf 'port=8080\r\nhost=a\r\n' > dos.conf
ln -s config.conf lien.conf

export LC_ALL=C.UTF-8 makes sed print its messages in English, as shown here. In config.conf (eleven lines), host=serveur serveur is line 2, port=8080 is line 3, and [db], [web], [cache] open sections. app.conf is used by the anatomy and the map, dos.conf has Windows line endings and lien.conf points to config.conf. The file contents use French words, which the commands keep: serveur is "server" and lien is "link". The outputs come from GNU sed 4.9, tested on Debian 13, AlmaLinux 10 and Ubuntu 26.04. The sed of macOS or BSD differs: see "Pitfall: -i is not written the same way on macOS and BSD".

The sed command in detail

A sed command is always written in the same order: the options, then the script between single quotes, then the file. The script holds an address, which chooses the lines, and an action, which says what to do with them. In the example below, without /^port=/ every line is processed; without -n every line is printed.

Anatomy of the command

Syntaxsed [options] '[address]command' [file...]

  1. sed the programThe command run in the shell. It reads text and writes nothing to the file by default.
  2. -n an optionoptionalChanges the behaviour: -n cuts printing, -i writes to the file, -E turns on extended regexes, -e adds a command.
  3. /^port=/ the addressoptionalSelects the lines: a number (3), a pattern (/^port=/), a range (2,5). Without an address, every line.
  4. s the sed commandWhat to do with the line: s replaces, d deletes, p prints, a\ appends after it.
  5. 8080 the patternA regular expression, between two / delimiters.
  6. 9090 the replacementThe text put in its place. & recalls the matched text.
  7. p the flagoptionalRefines s: g for every occurrence, 2 for the second one, I ignores case, p prints the replaced line.
  8. app.conf the fileoptionalOne or more files. Without a file, sed reads standard input, so the output of a pipe.

Outputport=9090

How sed reads a file, line by line

sed repeats the same cycle for each line: it reads it, applies the commands to it in order, then prints it. The map follows its working copy (the pattern space) on app.conf. Before clicking, note how many lines come out on screen and what app.conf contains: with no option, with -n, with -i, with both. Then check with the map.

Mental model

How sed processes a file

read a lineapply the commands, in orderprint and start again, line after line

$ sed -e '/^#/d' -e 's/localhost/0.0.0.0/' app.conf

  1. sed reads line 1, “# serveur”, and copies it into the pattern space.
  2. /^#/d matches: the line is deleted from the pattern space. The cycle stops here, with nothing printed.
  3. sed reads line 2, “host=localhost”, and copies it into the pattern space.
  4. /^#/d does not match: the line does not start with #, so it stays.
  5. s/localhost/0.0.0.0/ matches: the first occurrence is replaced in the pattern space.
  6. End of the cycle: sed prints the pattern space, then moves to the next line.
  7. sed reads line 3, “port=8080”, and copies it into the pattern space.
  8. /^#/d does not match: the line does not start with #, so it stays.
  9. s/localhost/0.0.0.0/ does not match: nothing changes, and this is not an error.
  10. End of the cycle: sed prints the pattern space, then moves to the next line.
  11. No more lines to read. app.conf has not changed: the result is only displayed.

What the animation shows

  1. One line at a time. sed does not load the file into memory: it reads it as a stream, which also works on a huge file.
  2. Every command, in order, on each line. d stops the cycle: the following commands never see the line.
  3. Printing is automatic, at the end of the cycle. -n cuts it; you then need p to print a line.
  4. The file does not change, except with -i: the output then replaces the file.

Golden rules

Preview before editing in place

Run the command without -i, read the result, then add -i. Or keep a copy, which a second pass with the same suffix will overwrite:

sed -i.bak 's/a/b/' file

Change the delimiter when the text contains /

The character that follows s becomes the delimiter:

sed 's#/var/www#/srv/www#' site.conf

Essential vocabulary

Commands · in the script, between the quotes

s/old/new/
Replaces the first occurrence of the lineecho aaa | sed 's/a/b/' → baa
s/old/new/g
Replaces every occurrenceecho aaa | sed 's/a/b/g' → bbb
d
Deletes the line and moves to the nextsed '/^#/d' app.conf → no comment left
p
Prints the line (often with -n)sed -n '2p' app.conf → host=localhost

Options · on the command line, before the script

-n
Cuts automatic printingsed -n '/port/p' app.conf → port=8080
-i
Writes the result to the filesed -i 's/8080/9090/' app.conf → app.conf modified, empty screen
-E
Extended regular expressionssed -E 's/[0-9]+/N/' app.conf → port=N on line 3
-e
Adds a command to the scriptsed -e '/^#/d' -e 's/8080/9090/' app.conf → two commands

The p command (print) prints the selected line, but sed already prints every line by itself. Predict what this command gives:

Terminal window
sed 'p' paths.txt | head -4
Output
/usr/local/bin/app
/usr/local/bin/app
/etc/app/app.conf
/etc/app/app.conf

p shows every line twice: the automatic print, then the p. The -n option turns off the automatic print: sed -n '2p' paths.txt prints only line 2. The q command stops sed after the current line (sed '2q' paths.txt), which avoids reading the rest of a file of several gigabytes.

Replace a word with s

The s command (substitute) is written s/old/new/: sed looks for old in each line and replaces it with new.

First occurrence, all occurrences

Line 2 of config.conf contains serveur twice; grep host keeps only that line.

Terminal window
sed 's/serveur/X/' config.conf | grep host
sed 's/serveur/X/g' config.conf | grep host
Outputs of the two commands
host=X serveur
host=X X

With no option, sed replaces the first occurrence of each line. The g flag replaces them all, and a number (s/serveur/X/2) targets the second one.

Change the delimiter

The character right after s becomes the delimiter. With a path, the most natural command fails, because sed takes the first / of the path for the end of the pattern.

Terminal window
sed 's//usr/local//opt/' paths.txt
Output (exit code 1)
sed: -e expression #1, char 8: unknown option to `s'

sed read the empty pattern //, then usr, then local//opt/ as flags: character 8 is the l of local. Protect each slash with \/, or choose a character that appears neither in the pattern nor in the replacement: sed 's#/usr/local#/opt#' paths.txt replaces /usr/local with /opt and prints /opt/bin/app as its first line.

A substitution with no effect is not an error

If the pattern matches no line, sed says nothing and returns code 0.

Terminal window
sed 's/zzz/y/' config.conf > /dev/null; echo rc_sed=$?
Output
rc_sed=0

A script that tests this code therefore believes the replacement happened. Check that a pattern finds something with sed -n '/zzz/p' config.conf (nothing comes out), or with sed -n 's/port=8080/port=9090/p' config.conf, which prints only the lines that were really replaced.

Chain several substitutions

A semicolon separates two commands of the same script, and -e passes them separately. sed applies them in order, to each line.

Terminal window
sed -e 's/usr/USR/' -e 's/var/VAR/' paths.txt

Lines 1 and 3 change (/USR/local/bin/app, /VAR/log/app.log), line 2 stays untouched.

Use a shell variable

Between single quotes, sed receives $valeur as it is. Between double quotes, the shell inserts the value, and two characters cause trouble:

Terminal window
valeur='R&D'; echo 'equipe=x' | sed "s/x/$valeur/"
chemin='/opt/app'; echo 'racine=x' | sed "s/x/$chemin/"; echo "code $?"
Output
equipe=RxD
sed: -e expression #1, char 6: unknown option to `s'
code 1

The & gives a wrong result with no message: in the replacement it stands for the matched text (\& for an ordinary &). The / closes the replacement too early, which another delimiter avoids (sed "s#x#$chemin#"). If you do not control the value, see "When to avoid sed".

Select lines with an address

An address goes in front of the command and limits its effect: 2s/serveur/X/ only changes line 2. It is tried here with d (delete), which removes the chosen lines from the output; no file is modified.

By line number

A number designates a line, two numbers separated by a comma a range (bounds included), $ the last line.

sed '2d' paths.txt removes line 2, /etc/app/app.conf, from the output and prints the two other paths.

By pattern

A pattern between / selects the lines that contain it. sed '/^#/d' config.conf removes the comments: the ^ anchor limits the pattern to lines that start with #, and without it a useful line followed by a comment would disappear too. The dot . accepts any character: /app.conf/ also matches appXconf, and \. aims at a real dot.

Everything except an address

A ! between the address and the command reverses it: sed '/app\.conf/!d' paths.txt deletes the lines that do not contain app.conf, and prints only /etc/app/app.conf.

Between two patterns

A range starts at a line that matches the first pattern and ends at the first following line that matches the second. Square brackets have a meaning in a pattern, so they are protected with \[ and \].

Terminal window
sed '/\[db\]/,/\[web\]/d' config.conf
Output
# configuration
host=serveur serveur
port=8080
port=80
date=2026-11-24
[cache]
debug=false

Both bounds are deleted with the range: [web] is gone, and port=80 ends up outside any section. To keep the end bound, group in braces a command that only targets the lines of the range: !d deletes those that do not contain [web], which gives sed '/\[db\]/,/\[web\]/{/\[web\]/!d}' config.conf.

A finished range reopens at every new start. If the second pattern matches no line, it runs to the end of the file, with no message and with code 0:

Terminal window
sed '/\[db\]/,/\[zzz\]/d' config.conf
Output
# configuration
host=serveur serveur
port=8080

With -i, the file would really be cut down to three lines. Before any deletion, print the range: sed -n '/\[db\]/,/\[zzz\]/p' config.conf.

Substitute on some lines only

In front of s, an address limits the replacement: sed '3s/port=.*/port=9090/' config.conf only touches line 3. With a range, only the lines of one section are concerned, and diff shows the change without printing eleven lines:

Terminal window
sed '/\[db\]/,/\[web\]/s/^port=.*/port=6543/' config.conf | diff config.conf -
Output
6c6
< port=5432
---
> port=6543

Only one line differs, the one in [db]: the two other port= lines do not move.

One line changed too many Exercise 1 of 2 · ~5 min · terminal

A colleague wants to change the port of the [web] section from 80 to 8000 in config.conf. They run sed 's/port=80/port=8000/' config.conf | diff config.conf -, without -i to check first, and expected a single modified line. What do they see, why, and how do you change only the port of [web]?

Run the colleague's command, then fix it

Terminal window
sed 's/port=80/port=8000/' config.conf | diff config.conf -

Count the lines diff reports and their value, then write a command that only changes the port of [web], with the same | diff config.conf -.

I have tried: show the solution
Output of the colleague's command
3c3
< port=8080
---
> port=800080
8c8
< port=80
---
> port=8000

The pattern port=80 is not anchored: it also matches the start of port=8080, hence port=800080, with no message and with code 0. Two fixes give a single modified line, 8c8:

Terminal window
sed 's/port=80$/port=8000/' config.conf | diff config.conf -
sed '/\[web\]/,/\[cache\]/s/port=80/port=8000/' config.conf | diff config.conf -

The $ anchor requires port=80 to end the line. The range limits the change to [web]. In a bigger file, combine the two: the range and port=80$.

Reuse the matched text: & and groups

In the replacement, & stands for the text the pattern matched.

Terminal window
sed 's/port/[&]/' config.conf | head -3
Output
# configuration
host=serveur serveur
[port]=8080

The first two lines do not contain port and pass through as they are; the third shows [port].

Groups reorder pieces

With -E, parentheses form a group numbered from left to right, and \1, \2 put it back in the replacement.

Terminal window
sed -E 's/^([a-z]+)=(.*)$/\2=\1/' config.conf | head -3
Output
# configuration
serveur serveur=host
8080=port

Group 1 captures host, group 2 the rest of the line, and \2=\1 swaps them. The comment line does not match the pattern and stays untouched. The greediness of .* and the reordering of a date are covered in Regular expression basics.

Add a line

The a\ command appends text after the chosen line, i\ inserts before, c\ replaces it (table at the end of the lesson). To append delai=30 after line 2, only the start of the result is printed:

Terminal window
sed '2a\delai=30' config.conf | sed -n '1,4p'
Output
# configuration
host=serveur serveur
delai=30
port=8080

With a pattern as the address, anchor it: port=80 would also match port=8080, and the text would be appended after both lines. The text that follows a\ keeps its leading spaces, whereas a without a backslash strips them: prefer a\ in a file where indentation matters, a YAML file for example.

Edit a file in place with -i

The -i option (in place) saves the result into the file instead of printing it. Always run the command without -i first and read the output, then run it again with -i.

What -i does to the file

sed -i writes the result into a temporary file, then renames it over the original. This explains the symbolic link pitfall and the write permission on the folder, which -i needs to create that temporary file.

Keep a backup with -i.bak

A suffix glued to -i keeps the original under that name; without a suffix, nothing is kept. Work on a copy:

Terminal window
cp config.conf work.conf
sed -i.bak 's/8080/9090/' work.conf
echo work:; sed -n 3p work.conf
echo bak:; sed -n 3p work.conf.bak
Output
work:
port=9090
bak:
port=8080

The suffix is glued to the option: with a space, sed -i .bak 's/80/90/' work.conf reads .bak as the script and fails with unknown command: `.'. For the same reason, -iE creates a file ending in E without turning on -E: write -Ei.

Edit several files at once

sed -i processes each file separately, like -s, and gives each one its backup. With neither -i nor -s, the numbering carries on from one file to the next: sed '1d' a.conf b.conf only removes line 1 of the first, sed -i '1d' a.conf b.conf that of both. To preview, add -s.

Pitfall: two passes overwrite the backup

Running sed -i.bak again on the same file replaces the .bak with the state from before the second pass: the original is lost, with no message. Exercise 2, in the section "Full case", has you practise it.

lien.conf is a link to config.conf. Edit it with -i, then compare:

Terminal window
sed -i 's/8080/9090/' lien.conf; ls -l lien.conf config.conf; sed -n 3p config.conf
Output on Debian 13 (AlmaLinux adds a dot after the permissions)
-rw-r--r-- 1 ansible ansible 123 Nov 24 19:37 config.conf
-rw-r--r-- 1 ansible ansible 123 Nov 24 19:37 lien.conf
port=8080

lien.conf starts with -: it has become an ordinary file, the link (which would start with l) is gone, and config.conf has not moved. To edit the target, add --follow-symlinks.

Pitfalls: -n with -i, q with -i, redirecting to the same file

With -n and p, sed -i only writes the lines that are printed; with q, only those read before it stops. A redirection empties the file being read:

Terminal window
cp paths.txt p3; sed 's/usr/USR/' p3 > p3; echo "code $?"; wc -c p3
Output
code 0
0 p3

The shell runs > p3 before starting sed: the file is emptied and sed reads an empty file, with code 0. To write into the file being read, use -i.

Pitfall: -i is not written the same way on macOS and BSD

On macOS and FreeBSD, -i requires a backup extension (-i extension, see the FreeBSD manual of sed): the sed -i 's/a/b/' file of this lesson is not valid there. The form sed -i.tmp 's/a/b/' file && rm file.tmp works on both. Choose a suffix that is not the one of your backups: with -i.bak followed by rm file.bak, an existing backup would be deleted too.

Full case: edit a configuration file and be able to roll back

Three values change: the host, the user of the [db] section and the debug mode. You preview with diff file -, which compares the file with what arrives through the pipe.

Terminal window
cp config.conf web.conf
sed -e 's/^host=.*/host=web1/' \
-e '/^\[db\]/,/^\[web\]/s/^user=admin$/user=app/' \
-e 's/^debug=.*/debug=true/' \
web.conf | diff web.conf -
Output
2c2
< host=serveur serveur
---
> host=web1
5c5
< user=admin
---
> user=app
11c11
< debug=false
---
> debug=true

Three lines change, the ones you wanted, and web.conf has not moved. You then write the same command with -i.orig, and compare:

Terminal window
sed -i.orig -e 's/^host=.*/host=web1/' \
-e '/^\[db\]/,/^\[web\]/s/^user=admin$/user=app/' \
-e 's/^debug=.*/debug=true/' \
web.conf
diff web.conf.orig web.conf

The diff prints the same three differences as the preview. If the service rejects the file, the backup puts it back:

Terminal window
mv web.conf.orig web.conf; diff config.conf web.conf; echo "code $?"
Output
code 0

diff prints nothing and returns 0: the file is back to its starting state. On a real server, edit the file under /etc: a file under /usr belongs to the package, whose update overwrites it.

Two passes without losing the original Exercise 2 of 2 · ~8 min · terminal

In a copy of config.conf named e.conf, 8080 becomes 9090, then serveur becomes srv everywhere. You must be able to get back to the starting state. A colleague advises -i.bak on every pass: check what that gives, then do it without losing the original.

Observe

Copy config.conf to e.conf, run the two passes with -i.bak, then print lines 2 and 3 of e.conf.bak.

Preview

Copy config.conf to e.conf again, delete e.conf.bak, then print the two changes with diff without modifying e.conf.

Write and compare

Write the two sed -i commands so that the original stays under e.conf.orig, then compare e.conf.orig and e.conf and read the exit code of diff.

Restore and check

Put e.conf back to its original state from the backup, compare it with config.conf and read the exit code.

I have tried: show the solution
Terminal window
cp config.conf e.conf
sed -i.bak 's/8080/9090/' e.conf
sed -i.bak 's/serveur/srv/g' e.conf
sed -n '2,3p' e.conf.bak
Output of step 1
host=serveur serveur
port=9090

The second pass replaced e.conf.bak: it holds the result of the first one (port=9090) and the original port=8080 is lost. The rest previews, then writes correctly:

Terminal window
cp config.conf e.conf; rm e.conf.bak
sed -e 's/8080/9090/' -e 's/serveur/srv/g' e.conf | diff e.conf -
sed -i.orig 's/8080/9090/' e.conf
sed -i 's/serveur/srv/g' e.conf
diff e.conf.orig e.conf; echo "code $?"
mv e.conf.orig e.conf; diff config.conf e.conf; echo "code $?"
Output
2,3c2,3
< host=serveur serveur
< port=8080
---
> host=srv srv
> port=9090
2,3c2,3
< host=serveur serveur
< port=8080
---
> host=srv srv
> port=9090
code 1
code 0

The suffix is only given on the first pass: the second one does not touch e.conf.orig, which keeps the state from before both passes. The first diff is the preview, the second returns 1 because the files differ, the last returns 0: e.conf is back to config.conf.

A file that came from Windows

A file created on Windows ends its lines with a carriage return (\r) followed by a line feed, and a substitution anchored on the end of the line no longer matches. cat -A makes hidden characters visible: $ marks the end of the line, ^M the carriage return.

Terminal window
cat -A dos.conf
sed 's/8080$/9090/' dos.conf | cat -A
sed 's/\r$//' dos.conf | cat -A
Outputs of the three commands
port=8080^M$
host=a^M$
port=8080^M$
host=a^M$
port=8080$
host=a$

The second command changed nothing and reported no error: the last character of the line is the carriage return, not the 0. s/\r$// removes the ^M; add -i to save.

Which command should I use?

To find a syntax again, start from the need.

I want to...I write
Replace every occurrence, or the second ones/old/new/g, s/old/new/2
Ignore case, convert to uppercases/word/X/gI, s/.*/\U&/
Substitute on one line, a range, the last line2s/a/b/, 2,3s/a/b/, $s/a/b/
Delete lines, comments, empty linessed '2d', sed '/^#/d', sed '/^[[:space:]]*$/d'
Remove trailing blankssed 's/[[:space:]]*$//'
Print some lines, their numberssed -n '2,3p', sed -n '/pattern/='
Insert before, replace a line2i\text, 2c\text
Edit the file, with a backup, on GNU and BSDsed -i.bak 's/a/b/' f, sed -i.tmp 's/a/b/' f && rm f.tmp
Edit the target of a link, preview several filessed -i --follow-symlinks 's/a/b/' link, sed -s '1d' a.conf b.conf

When to avoid sed: JSON, YAML, XML and server state

sed sees lines of text, not a structure: a substitution that works on a test file breaks as soon as the order of the keys or the indentation changes. Prefer jq for JSON, yq (in French) for YAML, xmlstarlet to edit XML and awk for columns. In Ansible, a sed -i run by shell is replayed on every run and appends the line twice: the lineinfile module (in French) checks the state of the file first. To inject variables into a template, envsubst (in French) avoids the problems with / and &.

Troubleshooting

Always run the command again without -i, and check the pattern alone with sed -n '/pattern/p' file: if nothing comes out, the pattern matches no line.

Message or symptomCodeLikely causeSolution
sed: can't read fichier: No such file or directory2Wrong file name, or wrong folderls, pwd, run again from ~/sed-lab
sed: -e expression #1, char 13: unterminated `s' command1The last delimiter is missing: s/serveur/srvWrite s/serveur/srv/
No message, text unchanged0Case, $ on a Windows file, \d (read as the letter d), + without -Ecat -A to see ^M, [0-9], -E
port=8080 becomes port=8000800Unanchored patternAnchor with $, or limit to a range
sed: couldn't open temporary file …: Permission denied4No write permission on the foldersudo, or work on a copy
A file ends with E after the command0-iE: the E is read as a suffix-Ei

sed returns 0 when it succeeded, even with no match, 1 for an invalid command, 2 for a missing file and 4 for an I/O error.

Clean up the practice folder

Delete the practice folder, that is ~/sed-lab and nothing else:

Terminal window
rm -r ~/sed-lab

Key points

  • sed writes the result to standard output and only modifies the file with -i; -n turns off the automatic print.
  • With no match, s returns 0: check with sed -n '/pattern/p'. An unanchored pattern also finds a longer text (port=80 in port=8080).
  • Both bounds of a range are deleted with it; with no end pattern, it runs to the end of the file.
  • -i.bak only keeps the state from before the last pass, -i processes each file separately (preview with -s), and it replaces a symbolic link with an ordinary file.
  • In a variable, & and / break s; an invisible \r stops $ from matching; on macOS and BSD, -i requires an extension.
  • For a configuration file: preview with | diff file -, write with -i.orig, compare, and mv puts the old content back.

Knowledge check

Check that the essentials of this guide stuck. The questions cover only what has just been explained here.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer

FAQ - Frequently Asked Questions

The questions most often asked about sed: what it does, replacing on a whole line, deleting lines, editing a file in place and keeping a backup.