Home·Terminal commands

sed

Text processing

Usage

sed -i 's/[old]/[new]/g' [file]

Edits text line by line, most often with s/old/new/; the in-place -i differs between GNU and BSD, and without a trailing g only the first match on each line changes.

Common flags

FlagMeaning
s/a/b/gReplace a with b; without the trailing g only the first per line
-iEdit in place. GNU takes -i alone, BSD and macOS need -i ""
-EExtended regex; BSD also accepts -r for GNU compatibility
-nPrint nothing unless a command says to, usually with p
-eAdd another expression to the script
-fRead the script from a file

Examples

sed -i 's/foo/bar/g' file.txt

Replaces every foo in place (GNU).

sed -i '' 's/foo/bar/g' file.txt

The same on macOS, with the empty argument.

sed -n '10,20p' file.txt

Prints only lines 10 to 20.

These were built to be piped together. Three joined commands are usually shorter than one that does everything.

How to read this

  • Square brackets [ ] mark a part you may leave out.
  • An ellipsis … means you can list more than one.
  • Flags are case-sensitive — in some commands -r and -R do different things.

Questions

Q. What does sed do?

Edits text line by line, most often with s/old/new/; the in-place -i differs between GNU and BSD, and without a trailing g only the first match on each line changes.

Q. How do I type it?

sed -i 's/[old]/[new]/g' [file] — square brackets mark the parts you can leave out.

Q. How many flags are worth knowing?

6 are listed here; the full set is in man sed. This command sits under Text processing.

Related commands

man page: man sed