December 4, 2026

sed Find and Replace: Tested Examples, Plus Two Ways It Can Empty or Break a File

A typewriter with one word on the page covered by correction tape

sed 's/old/new/' is the most typed command in text processing and the one people most often copy without reading. It replaces only the first match on each line, its default regular expressions ignore +, and its in-place flag can silently turn a symbolic link into an ordinary file or erase a file entirely. Every example below was run with GNU sed 4.9 on Ubuntu 24.04, and the output shown is what came back.

Video: Learn Linux TV on YouTube

The s command

Syntax

The GNU manual describes sed as a stream editor, used to perform basic text transformations on an input stream. It reads a line, runs its script against it, prints the result, and moves to the next line. The substitute command has the form s/regexp/replacement/flags.

The sample file for most examples, app.conf:

color=red
color=blue
# color=green
size=10
path=/usr/local/bin
$ sed 's/color/colour/' app.conf
colour=red
colour=blue
# colour=green
size=10
path=/usr/local/bin

The file on disk is unchanged. Output goes to the terminal unless redirected or edited in place, which comes later.

First match only, unless told otherwise

$ printf 'red red red\n' | sed 's/red/blue/'
blue red red
$ printf 'red red red\n' | sed 's/red/blue/g'
blue blue blue
$ printf 'red red red\n' | sed 's/red/blue/2'
red blue red

Without a flag, only the first match on each line changes. g replaces all of them. A number replaces only that occurrence: the manual’s wording is “Only replace the numberth match.” I makes the match case-insensitive, so s/error/E/gI turned Error ERROR error into E E E.

Machine cutting a sheet of paper

Slashes in the pattern

Pick another delimiter

Paths are full of the character the command uses as a separator. Escaping each one works:

sed 's/\/usr\/local\/bin/\/opt\/bin/' app.conf

It is also hard to read and easy to get wrong. The manual allows any other character: the / characters may be uniformly replaced by any other single character within a given s command. The same edit with a pipe:

$ sed 's|/usr/local/bin|/opt/bin|' app.conf | tail -1
path=/opt/bin

The variable that contains a slash

The delimiter problem comes back when the replacement is a shell variable. Double quotes let the shell expand it:

$ name=world
$ printf 'hello NAME\n' | sed "s/NAME/$name/"
hello world

Now the value is a/b:

$ v='a/b'
$ printf 'X\n' | sed "s/X/$v/"
sed: -e expression #1, char 7: unknown option to `s'

The shell turned the command into s/X/a/b/, which sed read as a replacement of a followed by an unknown flag b. When a variable holds paths or URLs, choose a delimiter that cannot appear in it, such as | or #.

Regular expressions: basic by default

The + that does nothing

$ printf 'version 1.2.3\n' | sed 's/[0-9]+/X/g'
version 1.2.3
$ printf 'version 1.2.3\n' | sed -E 's/[0-9]+/X/g'
version X.X.X

The first command ran without error and changed nothing. GNU sed uses basic regular expressions unless told otherwise, and in basic syntax, the manual says, +, ?, |, parentheses and braces need a backslash to act as special characters. Without one, the pattern looked for a digit followed by a literal plus sign. -E switches to extended syntax, where they work as expected.

Capture groups and the ampersand

Parentheses in the pattern capture text, and \1 to \9 put it back in the replacement. Swapping first and last names, in extended syntax:

$ printf 'John Smith\nJane Doe\n' | sed -E 's/([A-Z][a-z]+) ([A-Z][a-z]+)/\2, \1/'
Smith, John
Doe, Jane

The same edit in basic syntax needs every parenthesis escaped: s/\([A-Z][a-z]*\) \([A-Z][a-z]*\)/\2, \1/. Both produced Smith, John.

An unescaped & in the replacement stands for the whole match:

$ printf 'hello world\n' | sed 's/world/[&]/'
hello [world]

That makes a literal ampersand a trap. Replacing b with “R&D”:

$ printf 'a&b\n' | sed 's/b/R&D/'
a&RbD
$ printf 'a&b\n' | sed 's/b/R\&D/'
a&R&D

The unescaped version put the matched b where the ampersand was.

Hooks on a wall

Choosing which lines

Addresses

A command can be limited to certain lines by putting an address in front of it. The manual lists the forms: a line number, $ for the last line, a /regexp/, a range addr1,addr2, and first~step for every nth line. Adding ! after an address inverts it.

$ sed '2s/blue/green/' app.conf | head -2
color=red
color=green

$ sed '/^#/!s/color/hue/' app.conf | head -3
hue=red
hue=blue
# color=green

The second command changed every line that does not start with #, leaving the commented-out setting alone. That pattern, edit everything except comments, is the one most config changes actually want.

Printing and deleting

-n stops sed from printing every line automatically. In the manual’s words, sed then “only produces output when explicitly told to via the p command.” Together they turn sed into a line filter:

$ sed -n '/^size/p' app.conf
size=10
$ seq 1 10 > n.txt
$ sed -n '3,5p' n.txt
3
4
5
$ sed -n '0~3p' n.txt
3
6
9

d deletes instead. sed '/^#/d' app.conf printed the file without its comment line, and sed '3,$d' n.txt left only lines 1 and 2.

Adding lines

a appends text after a matching line, i inserts before it:

$ sed '/^size/a timeout=30' app.conf
color=red
color=blue
# color=green
size=10
timeout=30
path=/usr/local/bin

Several commands can run in one pass with repeated -e: sed -e 's/red/RED/' -e 's/blue/BLUE/'.

c replaces a whole matching line, which suits settings better than a substitution that has to match the old value:

$ sed '/^size/c size=99' app.conf
...
size=99
...

Did anything change?

sed’s exit status does not say. sed 's/zzz/yyy/' app.conf matched nothing and still exited 0. Two flags help. -n with the p flag prints only the lines where a substitution happened:

$ sed -n 's/color=/hue=/p' app.conf
hue=red
hue=blue
# hue=green

And the w flag writes changed lines to a file: s/blue/BLUE/w changed.txt left one line, color=BLUE, in changed.txt, a record of exactly what was edited. For a yes-or-no answer in a script, GNU sed’s q command takes an exit code: sed -n '/size/{q0}; $q1' app.conf exited 0 because the pattern was present, and the same command looking for zzz exited 1.

Editing in place

-i and a backup

-i writes the result back to the file. The manual explains how: output goes to a temporary file, which then replaces the original. Adding a suffix keeps a copy of the original:

$ sed -i.bak 's/size=10/size=30/' a3.conf
$ grep size a3.conf a3.conf.bak
a3.conf:size=30
a3.conf.bak:size=10

For anything that matters, the backup costs nothing.

What -i does to a symbolic link

Because -i replaces the file rather than writing into it, a symbolic link gets replaced too. The test: real.conf holding size=10, and link.conf a symlink pointing to it.

$ sed -i 's/10/40/' link.conf
$ ls -l
-rw-r--r-- link.conf
-rw-r--r-- real.conf
$ cat real.conf link.conf
size=10
size=40

The link is gone. link.conf is now an ordinary file with the change, and the real configuration file was never touched. A program reading real.conf still sees the old value.

The manual documents the fix, --follow-symlinks, which edits the link’s destination instead:

$ sed -i --follow-symlinks 's/10/50/' link.conf
$ ls -l
lrwxrwxrwx link.conf -> real.conf
$ cat real.conf
size=50

Configuration under /etc is often a symlink, managed by a package or a tool, which is exactly where this matters.

The -n -i combination

The manual also warns that combining -i with -n is risky. The test:

$ printf 'keep me\n' > e.txt
$ sed -n -i 's/keep/kept/' e.txt
$ stat -c %s e.txt
0

The file is now zero bytes. -n turned off automatic printing, nothing in the script printed, so nothing was written to the temporary file, and that empty file replaced the original. Adding p to the substitution, or dropping -n, avoids it.

Empty glass jar with a black metal lid

Three other jobs people use sed for

Windows line endings

sed 's/\r$//' file.txt

That removed the carriage return from each line, confirmed with od -c, which showed only \n endings afterwards.

Joining lines

The command that joins a file into one comma-separated line looks like this:

$ sed ':a;N;$!ba;s/\n/,/g' j.txt
a,b,c

It works by looping to pull every line into the buffer before substituting the newlines. paste -sd, j.txt gave the same a,b,c and is far easier to read. sed can do it; it is not the right tool.

Changing case of characters

The y command maps characters one to one. Listing the whole alphabet both ways converted hello to HELLO.

How fast it is, and where GNU differs

Speed

A 2,000,000-line, 33 MB file with one substitution per line took 0.33 seconds. sed reads one line at a time, so memory use stays flat however large the file gets. That is also why multi-line edits are awkward: the join example above has to work around the line-at-a-time design.

Not every sed is GNU sed

The behaviour above is GNU sed’s. Some of it is a GNU extension, including the I flag, first~step addresses and an exit code after q. macOS ships the BSD version, where -i expects a backup suffix as a separate argument, so a script using a bare sed -i 's/a/b/' file on Linux needs sed -i '' 's/a/b/' file on a Mac. The GNU manual covers the GNU version only, and the macOS difference was not tested here.

Sources

  • GNU sed manual (single-page edition): https://www.gnu.org/software/sed/manual/sed.html

719 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *