LinuxCommandLibrary

sed

Stream editor for text transformations

TLDR

Substitute all occurrences of "apple" with "mango" on all lines

$ [command] | sed 's/apple/mango/g'
copy
Replace in-place in a file (overwriting original)
$ sed -i 's/apple/mango/g' [path/to/file]
copy
Run multiple substitutions in one command
$ [command] | sed -e 's/apple/mango/g' -e 's/orange/lime/g'
copy
Use a custom delimiter (useful when pattern contains slashes)
$ [command] | sed 's#////#____#g'
copy
Delete lines 1 to 5 and backup original with .orig extension
$ sed -i.orig '1,5d' [path/to/file]
copy
Print only the first line to stdout
$ [command] | sed -n '1p'
copy
Insert a new line at the beginning of a file
$ sed -i '1i\your new line text\' [path/to/file]
copy
Delete blank lines from a file
$ sed -i '/^[[:space:]]*$/d' [path/to/file]
copy

SYNOPSIS

sed [options] 'script' [input-file...]

DESCRIPTION

sed (stream editor) is a powerful text processing tool that performs basic transformations on input streams (files or piped data). It reads input line by line, applies specified editing commands, and writes to standard output.
Common operations include search and replace (s///), deletion (d), insertion (i), and printing (p). sed uses regular expressions for pattern matching and supports both basic and extended regex syntax. Address ranges (line numbers or patterns) can target specific lines.

PARAMETERS

-i[suffix], --in-place[=suffix]

Edit files in place; optionally create backup with suffix
-e script, --expression=script
Add script commands to execute
-f file, --file=file
Read script from file
-n, --quiet, --silent
Suppress automatic printing; only print when p command used
-r, -E, --regexp-extended
Use extended regular expressions
-s, --separate
Treat files as separate rather than single stream
-z, --null-data
Separate lines by NUL characters
--debug
Annotate program execution
--help
Display help
--version
Display version

CAVEATS

The -i option modifies files directly; always test with output to stdout first or use backup suffix. Behavior of -i without suffix varies between GNU sed and BSD sed. Regular expression syntax differs between basic (default) and extended (-r) modes.

HISTORY

Created by Lee McMahon at Bell Labs in 1973-1974 as part of Unix. Based on the ed editor's scripting capabilities but designed for non-interactive stream processing. GNU sed extended the original with features like in-place editing and extended regex support.

SEE ALSO

awk(1), grep(1), tr(1), ed(1), perl(1)

> TERMINAL_GEAR

Curated for the Linux community

Copied to clipboard