This is an ongoing work in progress, please let me know if you have any suggestions/feedback.

Basic syntax

sed [ options ] script filename

Where script is either a single sed command or file of sed commands (must use with -f option). Sed commands look like this:

action/pattern/replacement/flag

Filename can be omitted if you’re piping in standard input.

Actions

  • p: print
  • s: substitute
    • s accepts the following flags which are appended to the end of the command (e.g. s/word/subsitute/g)
    • n (a number): replace the nth instance of of word on each matched line
    • g: replace all instances of word on each matched line
    • p: print a line each time a substitution is made (if there are multiple substitutions, the line will be printed more than once)
    • w file: write line to file when a substitution is made.
  • d: delete line

Options

  • -e: reads the following argument as a script (allows for multiple instructions to be passed at once)
  • -n: only print lines to terminal if explicitly specified with the p command
  • -f: reads the following argument as a sed script saved as a file

Examples

Basic

Print lines matching a pattern to stdout:

sed -n '/pattern/p'' infile.txt

Delete lines matching a pattern and write to outfile:

sed '/pattern/d' infile.txt > outfile.txt

Replace word with replacement once on each line

sed 's/word/replacement/'

Replace every instance of word with replacement on each line

sed 's/word/replacement/g'

Replace nth character in file with X

sed 's/./X/n'

More complex

Replace all instances of foo with bar in .sh files unless they are hidden (begin with .)

find . -type f -name "*.sh" -not -path '*/\.*' -exec sed -i 's/foo/bar/g' {} +