sed By Examples

sed is a stream editor command available on all Unix-compatible systems. sed is quite a powerful tool, but the learning curve is also high comparing to other similar tools such as grep or awk. Almost every time I want to do something with sed, I need to look it up and search for some examples. So, I decided to compile a concise tutorial for sed that covers the most common useful use-cases.

With sed, you usually specify a few options and a script and feed it with an input file.

sed <options> <script> <input_file>

Options

Here are some options for sed command that you most likely need to know about them.

OptionDescription
-iEdits the input file in-place.
-eSpecifies the scripts for editing.
-nSuppresses printing each line of input.

Commands

Here are some common commands that you may use in sed scripts:

CommandDescription
gGlobal applies a command to every line of input.
pPrints the matching patterns to standard output.
dDeletes the matching patterns from output or input file.
s/regexp/replacement/Replaces a regexp instance with the replacement.

Examples

ExampleDescription
sed -n '2p' input.txtShows a single line by line number.
sed -n '2!p' input.txtShows all lines except one line number.
sed -n '2p;4p' input.txtShows multiple lines by line numbers.
sed -n '2,4p' input.txtShows multiple lines by a range.
sed -n '2,4!p' input.txtShows all lines except a range of lines.
sed -n '2,$p' input.txtShows all lines after a line number.
sed -n '2,$!p' input.txtShows all lines before a line number.
sed -i '2d' input.txtDeletes a particular line in-place.
sed -i '2,4d' input.txtDeletes a range of lines in-place.
sed -i '/regex/d' input.txtDeletes all lines matching regex in-place.
sed -i '/regex/,$d' input.txtDeletes all lines after a line matching regex in-place.
sed -i 's/foo/bar/g' input.txtReplaces all occurrences of foo with bar in-place.

Read More