IngmarBoddington
5/22/2013 - 4:30 PM

sed Linux stream editor command basic use and useful examples

sed Linux stream editor command basic use and useful examples

sed -n '<int>,<int>p' <file>
  - Grab contents of file between lines (inclusive)

sed [-n] '/<regex>/<command>' <inputfile> [> <outputfile>]
    - Fine lines with text in inputfile and optionally put in outputfile
    - -n makes command silent
    - use !d or p (with -n) to show only matched lines

sed 's/<regex>/<replace>/' <inputfile> [> <outputfile>]
    - Replaces matches text in infile and optionally put in outputfile
    - Use N; before s to check multiple lines
    - Use escaped brackets to capture and \<int> to use
      e.g. 's/\(capture\)/\1/"

sed -i .....
  - Replace given file with result in place

sed ':a;N;$!ba;s/\n/ /g' file
 - Replace newlines with spaces

sed 's/[[:space:]]*$//' file
 - Remove all trailing whitespace

sed -i "N;s/\(if[^{]*\)\n/\1/;P;D" file;
  - If opening brace after if on next line, bring to same line

grep -rl <match> <dir> | xargs sed -i 's/<match>/<replace>/g'
  - Replace string matches in all files in a directory

N adds next line to buffer
P prints top line
D deletes top line and continues

In replace:
  \U Makes all text to the right uppercase.
  \u makes only the first character to the right uppercase.
  \L Makes all text to the right lowercase.
  \l Makes only the first character to the right lower case. (Note its a lowercase letter L)

\s for spaces


Example for getting value from messed up XML:
sed -e 's/<\/customerFacingServiceId>/<\/customerFacingServiceId>\n/g' file | sed -n 's/.*<customerFacingServiceId>\([^<]*\)<\/customerFacingServiceId>.*/\1/p'