Skip to content

Text processing

12 min

sed is a language

An address selects; a command acts.

sed is usually met as one incantation — sed 's/a/b/' — and treated as a search-and-replace with options. It is not. It is a small language with a loop you did not write: read a line into the pattern space, run every instruction against it, print it, repeat.

Every instruction is an *address* and a *command*. 2d deletes line two. /ERROR/d deletes every line matching. 2,/ERROR/d deletes from line two to the next match. The comma is a range, not a list.

Try this

-n stops the automatic print, which turns sed from a filter that edits into one that selects. sed -n '/x/p' is grep.

The delimiter of s is whatever character follows it. That is the single most useful thing to know about sed, because it is how a path stays readable: s|/usr/bin|/opt/bin| needs no escaping at all.

In the replacement, & is the whole match and \1 is a capture group. Without g only the first match on each line changes — and g means global to the line, not global to the file.

Try this

-i edits the file in place, and it is the flag worth being careful with: there is no undo and no output to check first. The habit that survives contact with a real directory is to run it without -i, read what comes out, and only then add it.

A second buffer, the hold space, is what makes sed able to do things a single pass over one line cannot. 1!G;h;$!d reverses a file — six characters of loop and two of buffer.

Try this

sed -i on a file you have not backed up, with a pattern you have not tested, is the shape of most one-line disasters.

$

Files

The files in the sandbox, with their modes, link counts and sizes
ModeLinksSizeName
-rw-r--r--1812app.log
-rw-r--r--1404app.log.1