sed

GNU docs -> https://www.gnu.org/software/sed/manual/sed.html

  • Stand input = standard input stream, etc…

  • Used for basic transformation on streams

  • type -a sed 👉 sed is command, it is stand alone utility and not a shell built in

  • man sed 👉 to view documentation

  • Substitute command sed "s/[search-pattern]/replacement-string/" [File to execute this command on]

    • it does not alter the content of the file yet, it only send the output to STDout
  • case sensitive my default

    • i flag to ignore string, usage sed 's/search-pattern/replacement-string/i' [filename] - we also use capital I.
  • In case of multi line text it searches for text line by line and replaces its first match and then moves on

    • that is if there are two matches in a line it will replace only the first match

    • g - global replace to replace all the matches sed ’s/search-pattern/replacement-string/g' [filename]

    • If we want only a particular match to be replace we can use the number flag like 1, 2, 3…etc

  • we can write to new file using the > operation

    • -i: for inline editing. Append something to -i flag to create a backup file and replace inline for original file. Example: sed -i.bak 's/search-pattern/replacement-string/' [filename]
  • Any character following the s can be used as delimiter

    • ex: sed ’s#/home/json/#/something# , here # is used a delimiter.
  • Delete the content using d command

    • to delete the line containing this - sed ‘/this/d’ [filename]
  • Multiple sed

    • seperate each with semicolon - sed ‘/^#/d ; /^$/d' [filename]

    • using -e option one for each sed operation

      • sed -e ‘/^#/d’ -e ‘/^$/d’ [filename]
  • Run sed command from a file: (a file has all the sed commands we want to execute)

    • Example scripts.sed file to be
/^#/d
/^$/d
  • We can run sed from this file using -f flag - sed -f script.sed [filename to execute sed on]

  • To execute only against single line in the file

    • sed ‘2 s/apahe/httpd/‘ [filename]