sed Commands Reference

All sed commands, addresses and flags with examples for stream editing.

Searchable sed command reference covering line and regex addressing, the substitute command and its g/N/p/i flags, append/insert/change/delete editing, hold-space and branching commands, plus command-line flags like -n, -i and -E.

What does the -n flag do in sed?

By default sed prints every line after processing. The -n flag suppresses that automatic printing, so output appears only where you explicitly use the p command or the p flag on a substitution. It is the basis of sed -n '5p' to print one line.

sed

sed is a non-interactive stream editor: it reads input line by line into a buffer called the pattern space, applies a script of editing commands, and writes the result out. It excels at find-and-replace, deleting or printing selected lines, and multi-line transforms via the hold space. This page is a searchable, offline reference to sed’s addresses, commands, substitute flags and command-line options, each with a working example.

How it works

Every sed command may be prefixed with an address that selects which lines it applies to:

  • Addresses can be a line number 3, the last line $, a regex /re/, a range 2,5 or /a/,/b/, GNU step form 1~2, or a negated form addr!.
  • The substitute command s/regex/replacement/flags is the workhorse. Flags include g (all matches), a number N (the N-th match), p (print on change), i (case-insensitive) and m (multi-line). In the replacement, & is the whole match and \1..\9 are captured groups.
  • Editing commands add (a), insert (i), change (c), delete (d), print (p), transliterate (y) and quit (q).
  • Advanced commands move text between the pattern and hold spaces (h, H, g, G, x) and branch with labels (:label, b, t, T) for loops.

The output model matters: with no -n, sed prints the pattern space at the end of each cycle; with -n it prints nothing unless you ask.

Tips and examples

Delete blank lines and comment lines:

sed '/^$/d; /^#/d' config

Replace every tab with a comma across the whole file, in place with a backup:

sed -i.bak 's/\t/,/g' data.tsv

Print only lines 10 through 20:

sed -n '10,20p' file

Join all lines into one using the hold-space loop idiom:

sed ':a; N; $!ba; s/\n/ /g' file

Test changes by viewing output first, and only add -i once you are confident, since in-place editing rewrites the original file.