Featured image of post SED Cheatsheet

SED Cheatsheet

A quick reference table for SED commands

SED Reference Table

This table provides a quick reference for commonly used sed commands.

CommandDescription
sed 's/old/new/g' file.txtReplace all occurrences of “old” with “new” in file.txt “error”
sed -n '5p' file.txtPrint only the 5th line
sed -n '10,20p' file.txtPrint lines 10 to 20
sed 's/^/PREFIX: /' file.txtAdd a prefix to each line
sed 's/$/ SUFFIX/' file.txtAdd a suffix to each line
sed '3s/apple/orange/' file.txtReplace “apple” with “orange” only on the 3rd line
sed '/^$/d' file.txtRemove all blank lines
sed 's/[0-9]+/###/g' file.txtReplace all numbers with “###”
sed 's/[a-z]/\U&/g' file.txtConvert lowercase to uppercase
`grep “error” file.txtsed ’s/error/ERROR/g’`Find “error” and replace it with “ERROR”
`awk ‘{print $2}’ file.txtsed ’s/foo/bar/g’`Replace “foo” with “bar” in the second column
sed -e 's/dog/cat/g' -e 's/bird/fish/g' file.txtReplace multiple words in one command
sed 's/foo/bar/g' input.txt > output.txtSave the changes to a new file
sed 's/^[ ]*//' file.txtRemove leading spaces and tabs
sed 's/[ ]*$//' file.txtRemove trailing spaces and tabs

This reference should help you quickly find the sed command you need. Happy scripting! 🎩


References

  1. Wikipedia on sed: https://en.wikipedia.org/wiki/Sed
  2. GNU Sed Manual: https://www.gnu.org/software/sed/manual/sed.html
  3. Sed One-Liners: https://sed.sourceforge.io/sed1line.txt