delete last line from text file

I have a file with which i must remove the last line of the file (the footer). I know how to copy and redirect with tail -1 etc, but how do i delete it permanentely

My way to delete the last line of a file is with sed...

sed '$d' < input

Of course, to make this permanent, you need something like:

sed '$d' < input > tempfile
mv input input.old
mv tempfile input

Same as Perderabo's but a one liner

sed '$d' < file1 > file2 ; mv file2 file1

1 Like

Hi,

What does '$d' signify here? What if i want to delete the second last line. Do i have to use '$2d'?

Can you clarify?

Thanks,
Nisha

$ means the last line. But sed doesn't know that it has the last line until it arrives. You can't do a "sed '$-1d'" or anything. Deleting the next to the last line via sed is very hard. So hard that I would normally use other techniques. But just for the heck of it, I finally got a sed script running that deletes the next to the last line:

#! /usr/bin/sed -nf
#
${P
q
}
1{h
d
}
x
p

And this solution will not easily scale up. A sed script to delete $-2 will take about 10 times the code. Deleting $-3 would be a nightmare. The problem is that you don't know in advance how many lines there are. To really have a general solution, you need to make two passes through the file. On the first pass, you count the lines. On the second pass, you delete the appropriate line. sed cannot do this alone since it always will only make a single pass through the file.

#! /usr/bin/ksh
lines=$(wc -l $1)
((target=lines-1))
sed "${target}d" < $1
exit 0

Now we have an extensible solution.