Glossary

sed

sed (stream editor) applies editing commands to text as it flows from input to output. It is not interactive: you give it a script of commands, and it processes each line, producing transformed output. sed is descended from ed, the original Unix line editor, and inherits its somewhat cryptic command syntax.

The most common use is substitution:

sed 's/foo/bar/' file             # first occurrence per line
sed 's/foo/bar/g' file            # all occurrences
sed -i 's/foo/bar/g' file         # in place (GNU sed)
sed -i.bak 's/foo/bar/g' file     # in place with backup
sed -n '10,20p' file              # print lines 10-20
sed '/^#/d' file                  # delete comment lines
sed -e 's/a/b/' -e 's/c/d/' file  # multiple commands

Beyond substitution, sed has commands for deleting, inserting, appending, printing, branching, and holding text in a secondary buffer—enough power to do surprisingly complex transformations entirely within sed, though anything non-trivial is usually easier in awk or Python.

For simple substitutions, sed is unmatched for speed and terseness. For heavily structured transformations, consider awk. For anything involving JSON, use jq. Use the right tool for the shape of the data.

Related terms: grep, awk, Regular Expression

Discussed in:

Also defined in: Textbook of Linux