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
| Flag | Meaning |
|---|---|
| s/a/b/g | Replace a with b; without the trailing g only the first per line |
| -i | Edit in place. GNU takes -i alone, BSD and macOS need -i "" |
| -E | Extended regex; BSD also accepts -r for GNU compatibility |
| -n | Print nothing unless a command says to, usually with p |
| -e | Add another expression to the script |
| -f | Read the script from a file |
Examples
sed -i 's/foo/bar/g' file.txtReplaces every foo in place (GNU).
sed -i '' 's/foo/bar/g' file.txtThe same on macOS, with the empty argument.
sed -n '10,20p' file.txtPrints 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