The Sed Cheatsheet thumbnail

The Sed Cheatsheet

Sed is really a great tool to filter & transform text — but the syntax is not always easy. Whether you’re a beginner or a more advanced user looking for a memory aid, this cheatsheet will help you remember the basic sed commands.

Thank you for having registered with Yes, I Know IT !
You will receive your link to the free PDF in few seconds. Watch your mailbox !
If you have any issue, don't hesitate to contact directly sylvain@yesik.it

I’ve drawn that railroad-style infographic so you can have all in one page the basic syntax of the sed command.

Just start at the top of the page with the sed command, and follow the tracks, choosing the option you need at each intersection. For example:

  • To display system users & their default login shell, you will write:

    sed -e 's/:.*:/:/' /etc/passwd
    The substitution command will tell _sed_ to replace
    any text between the first and the last colon of each line by a single
    colon -- effectively removing any content between colons of the original file.
    The original file remains unchanged, and the output is sent to the standard output
    (the terminal)
  • To list last logged in users except for root, you will write:

    last | sed '/^root /d'
    A really common use of _sed_ in being part of a pipeline. Here I use
    it to filter out -- using the (d)elete command -- all lines starting by
    the word `root` (`^` means the start of the line).
  • To add C-style comments around some code snippet, you will write:

    sed -i -e '1i/*' -e '$a*/' code.snippet
    or, using only the POSIX syntax:
    sed -e '1i\
    /*' -e '$a\
    */' code.snippet > tmp.file
    mv -f tmp.file code.snippet
    The (i)nsert command add text _above_ the selected line. And the (a)ppend command
    adds text _after_ it. Among other improvements, GNU sed adds the `-i` option
    to change files in place (instead of manually creating temporary files). And
    the `i` and `a` commands can be written in only one line.
Share