1752271 Members
4707 Online
108786 Solutions
New Discussion юеВ

Delete last two lines

 
SOLVED
Go to solution
parmy_4
Occasional Contributor

Delete last two lines

Hi,
I have a file in which I don't need the last two lines. How can run a command to achieve this?

I have a work around for my collegue but he is not happy with it.

sed '$d' my_file | sed '$d'

I am expecting some thing like

sed -e '$d' -e '$d' my_file.

Please help us.
Parmy
17 REPLIES 17
Pete Randall
Outstanding Contributor

Re: Delete last two lines

Parmy,

Use "sed -e '$d' my_file |sed -e '$d'"

that should do it.


Pete

Pete
harry d brown jr
Honored Contributor

Re: Delete last two lines

vi my_file<
live free or die
harry
Live Free or Die
Jean-Luc Oudart
Honored Contributor

Re: Delete last two lines

with vi cmd
vi +$ my_file<
Regards
Jean-Luc
fiat lux
harry d brown jr
Honored Contributor

Re: Delete last two lines

Another way:

expr `wc -l my_file | cut -d" " -f1` - 2 | xargs echo | sed -e "s/^/head -/" -e "s/$/ my_file/" | sh > new_my_file

live free or die
harry
Live Free or Die
john korterman
Honored Contributor
Solution

Re: Delete last two lines

Hi,

I think this works (at least it seems so on my screen):

# tail -2 | comm -23 -

regards,
John K.
it would be nice if you always got a second chance
Jean-Luc Oudart
Honored Contributor

Re: Delete last two lines

awk solution :
awk -v nb=$(wc -l my_file | cut -f1 -d" ") '{if(NR>(nb - 2)) exit; print}' my_file

Regards,
Jean-Luc
fiat lux
Elmar P. Kolkman
Honored Contributor

Re: Delete last two lines

A possible solution:

head $(wc -l my_file | awk '{print "-" $1 - 2}') my_file

In vi you can use the command:
$-1,$d
to delete the last two lines. Should work in ed too.

Or a complete awk solution:
awk '{ if (NR > 2) { print prev2 } prev2=prev1;prev1=$0}' < my_file
Every problem has at least one solution. Only some solutions are harder to find.
Bharat Katkar
Honored Contributor

Re: Delete last two lines

Hi
This works ..but don't know you like it or not.

# let A=`cat file1 | wc -l`-2
# head -$A file1 >file2

That works.
Regards,
You need to know a lot to actually know how little you know
Jan Sladky
Trusted Contributor

Re: Delete last two lines

hi Parmy,

I have no HP-UX where to try it but on Linux
exists the tac command (opposit to cat)

so maybe the following row will help you

tac file | sed '1,2d' | tac | tee file1


br Jan
GSM, Intelligent Networks, UNIX