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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
in sed $ is the last line so to delete the last line:
sed '$d' <file>
Method 2
$ for the last line:
sed '$d' file
Method 3
cat file.txt | head -n -1 > new_file.txt
Beware, it seems, depending on the last line of file.txt (if it ends with EOF, or n and then EOF), the number of lines in new_file.txt may be the same (as file.txt) after this command (this happens when there is no n) – in any case, the contents of the last line is deleted.
Also, note that you must use a second (intermediate) file. If you cat and redirect to the same file, you’ll erase it.
Method 4
head --lines=-1. I first stumbled across this possibility in the man-page for head on a SLES11SP2-system (coreutils-8.12-6.23.1)
tail and head are part of the coreutils-rpm (at least for rpm-based-systems).
According to the changelog of coreutils, this syntax is supported since coreutils-version 5.0.1
Bad news: According to the RH5-man-page this option is not described
Good news: It works with RH5 (so in your case: it works – at least with a current version of RH5).
rpm -q coreutils shows me (on CentOS 5.8):
coreutils-5.97-34.el5_8.1
I am not sure if RH5.5. already has the coreutils-version that supports it. But 5.5 has EoLed anyway.
Method 5
Linux
$ is the last line, d for delete:
sed '$d' ~/path/to/your/file/name
MacOS
Equivalent of the sed -i
sed -i '' -e '$ d' ~/path/to/your/file/name
Method 6
On Mac (BSD head/tail) you can use:
cat file.txt | tail -r | tail -n +2 | tail -r
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0