Operating System - HP-UX
1828236 Members
2680 Online
109975 Solutions
New Discussion

How to get all but last 2 lines from text file ?

 
SOLVED
Go to solution
Sammy_2
Super Advisor

How to get all but last 2 lines from text file ?

I have a 2gb text file that vi editor can't open. Need a command (tail/head, sed, etc) that will parse the file so I get all the lines except the last 2 lines in the file.
good judgement comes from experience and experience comes from bad judgement.
8 REPLIES 8
MattJ123
Frequent Advisor
Solution

Re: How to get all but last 2 lines from text file ?

make a shell script:

#!/usr/bin/ksh
COUNT=`cat filename | wc -l`
MINUS=$(($COUNT-2))
head -n $MINUS filename
Tom Danzig
Honored Contributor

Re: How to get all but last 2 lines from text file ?

awk '{z=y;y=x;x=$0;if(NR>2){print z}}' filename
Steven E. Protter
Exalted Contributor

Re: How to get all but last 2 lines from text file ?

numline=$(cat filename | wc -l)
(( numline = numline - 2))

counter=1

while read -r filedata
do
if [ $counter = $numline ]
then
exit 0
else
# do something with data
fi
(( counter = counter + 1)) #increment
done < filename


Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com
Kent Ostby
Honored Contributor

Re: How to get all but last 2 lines from text file ?

depending on the max length of a line (awk wont handle everything), you could do:

awk '{count++}count outputfile

Best regards,

Oz
"Well, actually, she is a rocket scientist" -- Steve Martin in "Roxanne"
TwoProc
Honored Contributor

Re: How to get all but last 2 lines from text file ?

Hey Matt (cousin?),

I've noticed in files that are unusually large, the head & tail commands kind of just poop-out on you. Meaning I've noticed that they generally can't handle more than "some number" of lines - but I forget how many -but I've run into it. On the other hand on small(ish) files I've used your approach often.

So, I'll have to go with S. Protter's suggestion...
We are the people our parents warned us about --Jimmy Buffett
Gerhard Roets
Esteemed Contributor

Re: How to get all but last 2 lines from text file ?

Hi Sam

Install vim :P. It is free and it handles big files a tad better.

Regards
Gerhard
Marlou Everson
Trusted Contributor

Re: How to get all but last 2 lines from text file ?

Another way:

cnt=$(cat infile | wc -l)
(( cnt = cnt - 2 ))
awk -v count=$cnt 'NR <= count {print $0}' infile > outfile

Marlou
Sammy_2
Super Advisor

Re: How to get all but last 2 lines from text file ?

thanks to all. Used Matthew simple script since it is easiest to understand. Like Tom, Marlou and Kent's awk way of doing thing. Will Try Steve script as well. Am sure works. Not too fan of VIM since I only do this once in a blue moon.
good judgement comes from experience and experience comes from bad judgement.