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 skip the next two, and so on.
  • sed ‘/”[a-z]/ s/”/_/g’
    • look for the pattern then apply the substitutions only on the lines with the match to the matched pattern.
  • sed ‘s/\([0-9]\)-\([0-9]\)/\2\1/g’
    • The parenthesis defined the capture groups 1 and 2 then the values of the groups were placed in reverse order.
      • Note: capture group “zero” (\0) is the whole match.


Excellent deep dive into all functionalities of Sed [Link]

Pear is also able to perform similar tasks with the following syntax:

perl -p -i -e 's#LOOKFOR#R#' myfile1 myfile2


Command-line JSON processor called jq in combination with sponge:

jq '."attributeName" = "value"' /PATH/fileName.json | sponge /PATH/fileName.json