I want to remove some n lines from the end of a file. Can this be done using sed?
For example, to remove lines from 2 to 4, I can use
$ sed
In docker, this worked for me:
head --lines=-N file_path >> file_path
This might work for you (GNU sed):
sed ':a;$!N;1,4ba;P;$d;D' file
This will remove the last 12 lines
sed -n -e :a -e '1,10!{P;N;D;};N;ba'
You could use head for this.
Use
$ head --lines=-N file > new_file
where N is the number of lines you want to remove from the file.
The contents of the original file minus the last N lines are now in new_file
You can get the total count of lines with wc -l <file>
and use
head -n <total lines - lines to remove> <file>
With the answers here you'd have already learnt that sed is not the best tool for this application.
However I do think there is a way to do this in using sed; the idea is to append N lines to hold space untill you are able read without hitting EOF. When EOF is hit, print the contents of hold space and quit.
sed -e '$!{N;N;N;N;N;N;H;}' -e x
The sed command above will omit last 5 lines.