Editing streams with sed

Beginner · 15 min

Use sed to substitute, delete and print lines as text flows past: s///, addresses, capture groups, in-place edits, and macOS BSD sed differences.

Before thisPipes and pipelinesSearching with grep

Learn Linux TV · 15 min

Editing streams with sed

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Learn Linux TVReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • sed reads lines, applies a script to each, and prints the result. It never changes the input file unless you ask with -i.
  • s/old/new/ replaces the first match on each line, s/old/new/g every match, and s/old/new/2 only the second. Any character can be the delimiter, such as s|/usr|/opt|.
  • An address before a command limits it: 2,3p, /grace/p, 1d, $d. With -n, only lines printed by p appear.
  • With -E you can capture groups and reuse them as \1 and \2, and & stands for the whole match. Quantifiers are greedy, so prefer [^>]* to .*.
  • On macOS, sed -i needs an argument: sed -i '' for no backup. GNU's bare sed -i, \+ in basic mode and one-line a text commands behave differently or fail.

Editing without opening an editor

You have a 200-line log and need to hide the client addresses before sending it to a colleague. Opening an editor and fixing 200 lines by hand is silly. You want to say “on every line, replace this pattern with that” and let the text flow through. A stream editor works on a stream: sed reads input line by line, runs your script on each line, and prints the result to stdout. The input file stays as it was.

Everything below ran on macOS with BSD sed.

Substitute: s/old/new/

$ echo 'hello world' | sed 's/world/shell/'
hello shell
$ echo 'a a a' | sed 's/a/X/'
X a a
$ echo 'a a a' | sed 's/a/X/g'
X X X
$ echo 'a a a' | sed 's/a/X/2'
a X a

By default only the first match on each line changes. g means all, and a number means that one. The / is just a delimiter. When the pattern contains slashes, choose another: echo '/usr/bin' | sed 's|/usr|/opt|' printed /opt/bin. The pattern is a regular expression, so . matches any character: echo 'a.b' | sed 's/./X/g' gave XXX, while s/\./X/g gave aXb.

Masking addresses in the log:

$ head -2 logs/access.log | sed -E 's/^[0-9.]+/x.x.x.x/'
x.x.x.x - - [2026-11-01T00:00:00Z] "GET / HTTP/1.1" 200 120
x.x.x.x - - [2026-11-01T01:13:00Z] "GET /login HTTP/1.1" 200 517

Groups and &

Parentheses capture part of the match, and \1, \2 reuse them. & means the whole match. -E selects extended syntax, where the parentheses need no backslash:

$ echo 'ada,91' | sed -E 's/([a-z]+),([0-9]+)/\2 \1/'
91 ada
$ head -2 logs/access.log | sed -E 's/.*"GET ([^ ]*) .*" ([0-9]+) ([0-9]+)$/\1 \2 \3/'
/ 200 120
/login 200 517

The second pulled path, status and bytes out of each line. One trap with &: echo 'ada,91' | sed 's/[0-9]*/<&>/' printed <>ada,91. [0-9]* matches zero digits, and it matches that empty string at position 0 first.

Greediness is the other classic. .* takes as much as it can:

$ echo '<b>x</b><b>y</b>' | sed 's/<.*>//'

$ echo '<b>x</b><b>y</b>' | sed 's/<[^>]*>//g'
xy

Addresses: choose the lines

A command can be prefixed with a line number, a range, or a pattern. -n switches off automatic printing, so p prints only what you select:

$ sed -n '2,3p' data/people.csv
ada,infra,london,91
linus,kernel,portland,88
$ sed -n '/grace/p' data/people.csv
grace,compilers,new york,95
$ sed '1d' data/people.csv | head -2
ada,infra,london,91
linus,kernel,portland,88
$ sed '$d' data/people.csv | tail -1
ken,tools,murray hill,79

$ is the last line, d deletes. sed 5q prints five lines and quits, which makes it faster than head on nothing but is just as readable. Without -n, p doubles lines (echo hi | sed p printed hi twice). Multiple commands go in -e pieces or separated by semicolons: sed 's/foo/1/;s/bar/2/'.

y/el/ip/ translates characters like tr, so echo hello | sed 'y/el/ip/' gave hippo. Shell variables work if you use double quotes, which let the shell substitute first: sed "s/$v/there/" replaced world, while single quotes searched for the literal text $v and changed nothing.

In-place edits and the BSD trap

sed -i edits a file directly. Here macOS and Linux diverge, and a pasted one-liner behaves badly:

$ sed -i 's/ada/ADA/' p.csv
sed: 1: "p.csv": extra characters at the end of p command
$ sed -i '' 's/ada/ADA/' p.csv; sed -n 2p p.csv
ADA,infra,london,91
$ sed -i.bak 's/ada/ADA/' p.csv; ls p.csv*
p.csv
p.csv.bak

On BSD, -i takes a mandatory suffix argument, so -i 's/ada/ADA/' made sed read the script as a suffix and then try p.csv as a command. -i '' means no backup and -i.bak keeps one. GNU sed -i takes the suffix attached, so the portable form is -i.bak followed by deleting the backup. A nastier variant: sed -i -e 's/ada/ZZ/' q.csv ran silently and left a stray file called q.csv-e, because BSD took -e as the suffix. Check the directory after trying GNU-style flags.

Remember too that -i writes a new file and renames it, so a hard link to the old file is no longer linked afterwards.

More BSD and GNU differences

  • \+ in basic mode isn’t supported by BSD sed: echo aaa | sed 's/a\+/X/' printed aaa, but sed -E 's/a+/X/' printed X. Use -E.
  • The one-line form sed '1a end' fails on BSD (command a expects \ followed by text). BSD wants the backslash-newline form I ran: sed '1i\ then a line starting top.
  • sed --version doesn’t exist (illegal option -- --).
  • Step addresses like 2~3p are GNU only. BSD errored.
  • s/hello/X/I (case-insensitive) worked on BSD.
  • \n in the replacement text did insert a newline here, and \t a tab.

I did not run GNU sed, so the GNU side comes from these error messages and what I remember of the manual.

About the video

Learn Linux TV’s “Linux Crash Course - The sed Command” was published 20 August 2021 and runs 15 minutes 25 seconds. The description says it explores sed, “the stream editor”, and shows the basics of manipulating text. It has no chapters. I couldn’t read a transcript and don’t know which commands it demonstrates, or whether it uses -i. It is made on Linux, so expect the GNU flavours of -i and \+ in it. English by title and description. It is the same channel that supplied the PATH and streams videos earlier in this roadmap.

What I did not run

GNU sed, multi-line scripts with hold space beyond a single N and a one-liner reverse (they worked, but are advanced), and sed -f script.sed.

Next

When the work is about columns and arithmetic rather than patterns, awk is the better tool: processing columns with awk.

Check yourself

  1. 01What is the difference between sed 's/a/X/' and sed 's/a/X/g' on the line 'a a a'?

    Without g, only the first match on each line changes, giving 'X a a'. With g every match changes, giving 'X X X'.

  2. 02You copy a GNU one-liner sed -i 's/ada/ADA/' file to your Mac and get an error. What do you write?

    sed -i '' 's/ada/ADA/' file, with an empty string as the backup suffix. BSD sed requires an argument after -i. To keep a backup use sed -i.bak.

  3. 03Why does sed 's/<.*>//' turn '<b>x</b><b>y</b>' into an empty line?

    The .* is greedy and matches as much as possible, from the first < to the last >. Use [^>]* to stop at the first closing bracket.

  4. 04How do you print only line 2 of a file?

    sed -n 2p file. The -n turns off automatic printing, and 2p prints just line 2.

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark