Delete last line from the file

  • I use sed to quickly delete lines with specific position as

    sed '1d'
    sed '5d'

    But, what if I want to delete the last line of the file and I don't know the count of lines (I know I can get that using wc and several other tricks).

    Currently, using a workaround with head and tailcombined with wc to do so. Any quick twists here?

    Which os? Some flavours have interesting options for `head` and `tail`...

    @Nils I am on 'Red Hat Enterprise Linux Server release 5.5 (Tikanga)'. Can you point for the options for `head` and `tail` you know of on different flavours?

    I did. See below.

  • h3rrmiller

    h3rrmiller Correct answer

    8 years ago

    in sed $ is the last line so to delete the last line:

    sed '$d' <file>

    Use `sed -i '$d' ` to edit file in place.

    What would be for deleting the last n lines, where n is any integer number?

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM