Simple usage of sed command
The following examples show you how sed command can be used as a powerful alternative to general commands like head, tail etc.
Let us consider the below input file for all the examples explained here.
[neo@techpulp ~]# cat input.txt Line1 Line2 Line3 Line4 Line5 Line6 Line7 Line8 Line9 Line10 Line11 Line12 Line13 Line14 Line15 Line16 Line17 Line18 Line19 Line20 [neo@techpulp ~]#
Print all lines
[neo@techpulp ~]# sed -e '' input.txt Line1 Line2 Line3 Line4 Line5 Line6 Line7 Line8 Line9 Line10 Line11 Line12 Line13 Line14 Line15 Line16 Line17 Line18 Line19 Line20 [neo@techpulp ~]#
Do not print first 10 lines of input. Here “d” stands for deletion.
[neo@techpulp ~]# sed -e '1,10d' input.txt Line11 Line12 Line13 Line14 Line15 Line16 Line17 Line18 Line19 Line20 [neo@techpulp ~]#
Print first ten lines of input
[neo@techpulp ~]# sed -e '1,10!d' input.txt Line1 Line2 Line3 Line4 Line5 Line6 Line7 Line8 Line9 Line10 [neo@techpulp ~]#
Display only first five lines
Here “p” stand for print and “-n” options negates default behaviour of printing.
[neo@techpulp ~]# sed -n -e '1,5p' input.txt Line1 Line2 Line3 Line4 Line5 [neo@techpulp ~]#
Display lines 1 to 5 and 10 to 12
[neo@techpulp ~]# sed -n -e '1,5p' -e '10,12p' input.txt Line1 Line2 Line3 Line4 Line5 Line10 Line11 Line12 [neo@techpulp ~]#
Do the same with the expressions delimited by new lines
[neo@techpulp ~]# sed -n -e '1,5p > 10,12p' input.txt Line1 Line2 Line3 Line4 Line5 Line10 Line11 Line12 [neo@techpulp ~]#
Do not display 1 to 5 and 10 to 12
[neo@techpulp ~]# sed -e '1,5d' -e '10,12d' input.txt Line6 Line7 Line8 Line9 Line13 Line14 Line15 Line16 Line17 Line18 Line19 Line20 [neo@techpulp ~]#
Delete all lines after 11
[neo@techpulp ~]# sed -e '11,$d' input.txt Line1 Line2 Line3 Line4 Line5 Line6 Line7 Line8 Line9 Line10 [neo@techpulp ~]#
Print lines after 11
[neo@techpulp ~]# sed -n -e '11,$p' input.txt Line11 Line12 Line13 Line14 Line15 Line16 Line17 Line18 Line19 Line20 [neo@techpulp ~]#
You can use !p or !d to negate the sed expression.

