Skip to content

sed

16 commands

A stream editor for filtering and transforming text: substitutions, deletions and in-place file edits.

  • text processing
  • regex

Install sed

sudo apt install sed

Substitution5

sed 's/<old>/<new>/' <file>

Replaces the first match on each line and prints the result; the file is unchanged.

Link
sed 's/<old>/<new>/g' <file>

Replaces every match on each line.

Link
sed 's/<old>/<new>/gI' <file>

Case-insensitive replacement (GNU).

Link
sed 's#<old>#<new>#g' <file>

Use a different delimiter when the pattern contains slashes.

Link
sed -E 's/(<regex>)/[\1]/g' <file>

Extended regex with capture groups; \1 refers to the first group.

Link

Editing files2

sed -i 's/<old>/<new>/g' <file>

Edits the file in place. On macOS/BSD use sed -i '' instead.

Link
sed -i.bak 's/<old>/<new>/g' <file>

Edits in place and keeps a backup with the given suffix.

Link

Selecting lines6

sed -n '<n>p' <file>

Prints only line n.

Link
sed -n '<a>,<b>p' <file>

Prints a range of lines.

Link
sed -n '/<start>/,/<end>/p' <file>

Prints everything between two patterns, inclusive.

Link
sed '/<pattern>/d' <file>

Deletes matching lines — here, comments.

Link
sed '/^$/d' <file>

Deletes empty lines.

Link
sed '<n>d' <file>

Deletes line n, such as a CSV header.

Link

Inserting3

sed '<n>i <text>' <file>

Inserts a line before line n.

Link
sed '/<pattern>/a <text>' <file>

Appends a line after each match.

Link
sed 's/^[ \t]*//;s/[ \t]*$//' <file>

Trims leading and trailing whitespace; several commands are separated by semicolons.

Link