To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.
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.
sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' : this will remove all the blank lines from end of the file. sed '$d' : this will remove the last line.
I don't know about sed
, but it can be done with head
:
head -n -2 myfile.txt
If hardcoding n is an option, you can use sequential calls to sed. For instance, to delete the last three lines, delete the last one line thrice:
sed '$d' file | sed '$d' | sed '$d'
From the sed one-liners:
# delete the last 10 lines of a file
sed -e :a -e '$d;N;2,10ba' -e 'P;D' # method 1
sed -n -e :a -e '1,10!{P;N;D;};N;ba' # method 2
Seems to be what you are looing for.
A funny & simple sed
and tac
solution :
n=4
tac file.txt | sed "1,$n{d}" | tac
NOTE
"
are needed for the shell to evaluate the $n
variable in sed
command. In single quotes, no interpolate will be performed.tac
is a cat
reversed, see man 1 tac
{}
in sed
are there to separate $n
& d
(if not, the shell try to interpolate non existent $nd
variable)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With