Let’s explore sed’s explicit delete command, which you specify by using the option 'd'.
Again, we are using the sample file named 'practice.txt' as an input to delete the lines. To do so, run the command "sed 'd' practice.txt".
As you see there is no outcome of the command, it is because 'd' option delete all the lines from the file if you don't mention specific pattern.
Incase, if you want to delete the last line of the file, you need to run the command "sed '$d' practice.txt" . Here $ represents the last line.
Incase, if you want to delete from third line to the last line of the file, you need to run the command "sed '3,$d' practice.txt"
Run the command "sed '1~3d' practice.txt". This will delete the first line and fourth line and so on till the file exhausted. Here '1 ' represents the starting number of the line and '3' represents three lines jump from first line we would to like delete.
I would like to delete the lines which contains the text "star". Run the command "sed '/star/d' practice.txt"
Just to let you know that this will not look exactly "star" word alone and it will delete "*star*" as well. * represents any characters after 'star'.
Deleting few lines (ranges) based on the pattern from a file
Let us see an example with the same "practice.txt" file. This time, we can look from the line which has "man" word to end of the file. To do so, run the command
"sed '/man/,$d' practice.txt". Remember this command will always consider for the first match and then process till last line as its mentioned $.
Let us see another example with the same "practice.txt" file. This time, we can look from the line which has "man" word and retrieve three lines after that. To do so, run the command "sed '/man/,+3d' practice.txt"
Let us see another example with the same "practice.txt" file. This time, we can look from the line which has "man" word and retrieve until tenth line. To do so, run the command
"sed '/man/,8d' practice.txt"
Let us see another example with the same "practice.txt" file. This time, we can look from the line which has "man" word and retrieve until another line contains "tan" . To do so, run the command "sed '/man/, /tan/d' practice.txt"
Hope you now understand how sed delete the line from the file based on the given condition 😀.