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.

Option Description
-i Edits the input file in-place.
-e Specifies the scripts for editing.
-n Suppresses printing each line of input.

Commands

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

Command Description
1 Applies a command to only to the first occurrence.
2 Applies a command to only to the second occurrence.
g Global applies a command to every occurrence.
i Matches in a case-insensitive manner.
p Prints the matching patterns to standard output.
d Deletes the matching patterns from output or input file.
s/regexp/replacement/ Replaces a regexp instance with the replacement.

Regular Expressions

Pattern Description
^ 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

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

Read More