Skip to content

Instantly share code, notes, and snippets.

@IngmarBoddington
Last active April 18, 2022 20:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IngmarBoddington/5628952 to your computer and use it in GitHub Desktop.
Save IngmarBoddington/5628952 to your computer and use it in GitHub Desktop.
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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment