Search code examples
seddelete-row

Delete second-to-last line of file using sed


I have a file.txt and I have to delete the second-to-last line of the file. The below three sed commands are able to print the second-to-last line. But I need to delete that line. Any help??

sed -e '$!{h;d;}' -e x file.txt

sed -n 'x;$p' file.txt

sed 'x;$!d' file.txt

$ cat file.txt
apple
pears
banana
carrot
berry

Can we delete the second-to-last line of a file:
a. not based on any string/pattern.
b. based on a pattern - if second-to-last line contains "carrot"


Solution

  • This might work for you (GNU sed):

    sed -i 'N;$!P;D' file
    

    This sets up a window of two lines in the pattern space and then prints the first of those whenever the second is not the last. The last line is always printed because the next line can not be fetched.

    Deleting the second-to-last line of a file based on a pattern can be achieved with:

    sed -i 'N;$!P;${/pattern.*\n/!P};D'