Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AWK one liner to print last footer of file

Status
Not open for further replies.

warcypher

Technical User
Jan 30, 2003
3
CZ
Hi,

I'm completely new to awk, anyway I have a request.

Currently I have a file with thousands of records. I want to print only the last 20 lines of the file and redirect it to another file.

So far,

for i in `tail -20 <file_name`
do
echo $i >> ztmp
done

I was wondering if this could be done in awk. My objective is to print only the footer which is 20 lines from the end of file and put in another file.

Any help would be great . . .

Thanks

Warcypher
 
What about

tail -20 filename > ztmp

You could use awk but would need an array and any of a multitude of ways to catch 20 rows and ultimately print the last 20. tac comes to mind if you have it but doing the same in awk isn't so great if you have thousands or more files.

If you have the line count as a passed in as a variable/argument, via BEGIN processing or via a system call you can do the math and then this is simple, cheap and fast.

Why not

cat <<EOF | ed -s filename
1,.-20d
w ztmp
q
EOF
Cheers,
ND [smile]

bigoldbulldog@hotmail.com
 
If you insist on using awk, this should do it.

BEGIN {
num = 20
}
{
ix++
if (ix>num) ix=1
a[ix] = $0
}
END {
for (j=0;j<num;j++) {
ix++
if (ix>num) ix=1
print a[ix]
}
} CaKiwi
 
Hi guys,

Sorry for the delay. Been working overtime here. I really appreciate your help. Could 'CaKiwi' just take me through the AWK script? Just want to understand it that's all.

Thanks again.

Regards

Zia

 
Sure. This part

{
ix++
if (ix>num) ix=1
a[ix] = $0
}

saves the last num lines (set to 20 in the BEGIN clause) in array a. When processing of the file is complete, the END clause prints out the saved lines.

If you have any more questions, feel free to ask.

If you really want a one-liner, try this.

awk -v n=20 '{a[ix=ix%n+1]=$0}END{for(j=0;j<n;j++)print a[ix=ix%n+1]}' filename


CaKiwi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top