Header Shadow Image


Keep last number of lines in a file

Here is a quick way to keep the last 5000 lines of a large file instead of entirely clearing it.  A little bit of AWK though a simple array and bob's your uncle:

root [XYZ01] /var/spool/mail: ls -altri test.txt daemon
 1067 -rw-rw—-    1 daemon   mail       51130586 Jan 31 07:30 daemon
 1061 -rw-rw—-    1 daemon   mail         186022 Feb  1 00:20 test.txt
root [XYZ01] /var/spool/mail: cp -ip daemon test.txt
overwrite test.txt? y
root [XYZ01] /var/spool/mail: ls -altri test.txt daemon
 1061 -rw-rw—-    1 daemon   mail       51130586 Jan 31 07:30 test.txt
 1067 -rw-rw—-    1 daemon   mail       51130586 Jan 31 07:30 daemon
root [XYZ01] /var/spool/mail: FILEN="test.txt"; tail -n 5000 $FILEN|awk 'BEGIN { FILEN="'"$FILEN"'"; } { ARY[CNT++]=””$0; } END { for ( KEY in ARY ) { print ARY[KEY] > FILEN; } }'
root [XYZ01] /var/spool/mail: ls -altri test.txt daemon
 1067 -rw-rw—-    1 daemon   mail       51130586 Jan 31 07:30 daemon
 1061 -rw-rw—-    1 daemon   mail         186022 Feb  1 00:21 test.txt
root [XYZ01] /var/spool/mail: wc -l test.txt
    5000 test.txt
root [XYZ01] /var/spool/mail:
root [XYZ01] /var/spool/mail:

 

Cheers,
Tom

Subscribe
Notify of
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

     
  Copyright © 2003 - 2025 Tom Kacperski (microdevsys.com). All rights reserved.

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License

 

0
Would love your thoughts, please comment.x
()
x
The IT Development and Technology Mini Vault | MicroDevSys.com
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.