sed is a stream editor command available on 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 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
1Applies a command to only to the first occurrence.
2Applies a command to only to the second occurrence.
gGlobal applies a command to every occurrence.
iMatches in a case-insensitive manner.
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.

Regular Expressions

PatternDescription
^Matches the beginning of lines.
$Matches the end of lines.
.Matches any single character.
*Matches zero or more occurrences.
[]Matches a class of characters.

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