Sed is a text/string editor command-line tool.

Follow the most basic commands:

  • sed ‘s/LOOKFOR/REPLACE/file.txt
    • reading the file, look for a pattern then replacing it when there is a match.
  • cat file.txt | sed ‘s/LOOKFOR/REPLACE/’
    • piping the input to sed.
  • cat file.txt | sed ‘s/LOOKFOR/REPLACE/’ output.txt
    • pipping the input and redirecting the output to a file.
  • sed ‘s/LOOKFOR/REPLACE/’ file.txt > output.txt
    • file input and output.
  • cat file.txt | sed ‘s/LOOKFOR/REPLACE/g
    • using global will not stop on the first match.
  • sed -i ‘s/LOOKFOR/REPLACE/’ file.txt
    • changes the original file in-line.
  • cat file.txt | sed ‘s/[0-9]/(%)/g’
    • percentage symbol represents the matching string.
  • cat file.txt | sed ‘s_[0-9]_(%)_g’
    • using other characters and delimiters.
  • cat file.txt | sed ‘s/\//*/g’
    • scaping special characters adding a backslash before them.
  • sed ‘s/[^0-9]/REPLACE/’ file.txt
    • replacing anything that is not a number.
  • sed ‘s/LOOKFOR/REPLACE/g;s/LOOKFOR/REPLACE/g’ file.txt
    • applying multiple iterations in the same command (separated by semicolon).
  • sed -f replacements.txt file.txt
    • loading a file with the patterns (one on each line).
  • sed -n ‘s/LOOKFOR/REPLACE/g’ file.txt
    • disabling the screen output.
  • sed -n ‘s/LOOKFOR/REPLACE/pg’ file.txt
    • only outputs the lines that had matches.
  • sed ‘s/LOOKFOR/REPLACE/Ig’ file.txt
    • case insensitive for patterns.
  • sed ‘/LOOKFOR/d‘ file.txt
    • deleting the matches.
  • sed ‘1!{s/LOOKFOR/REPLACE/g;}‘ file.txt
    • skipping the first line.
  • sed ‘4 q‘ file.txt
    • only loads the first 4 lines and then quit.
  • sed ‘5,$ d‘ file.txt
    • it starts from line 5 and deletes all the other lines.
  • sed ‘=‘ file.txt
    • printing the line number before printing the line.
  • sed ‘=’ file.txt | sed ‘N; s/\n/ /
    • printing the line number at the beginning of each line.
  • sed -n=‘ file.txt
    • printing only line numbers.
  • sed ‘$=’ file.txt
    • printing the line number of the last line (counting the number of lines).
  • sed ‘n;d‘ file.txt
    • printing even lines.
  • sed ‘1!n;d’ file.txt
    • printing odd lines.
  • sed -n ‘p;n;n‘ file.txt
    • printing one line and skipping the next two, and so on.