Mastering sed: part 1
In this tutorial, we will go over the basics of using sed, an ancient and powerful text manipulator. This tutorial assumes basic experience with bash.
We will go over real sed examples that you can copy paste into your own terminal which explore various features and fundamental ideas of sed. At the end, we will have a summary of the fundamentals.
Print the 2nd line
Example
echo 'first
second
third
fourth
fifth' | sed -n 2p
Output:
second
Explanation
There are 3 important ideas in this example:
2
Sed applies commands to an address within the text. Here our address is 2, which means the 2nd line (sed line numbers start from 1, not 0).
p
Sed commands are single letters. Here our command is p which means print.
-n
Normally sed prints every line after the command has been applied. However, when our command itself is print, we don’t want to see the other lines, so we use -n to tell sed not to print everything again.
Altogether
Altogether this forms a command, only print the 2nd line.