[Webinar] Streamline your web hosting managementRegister Today

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 230
  • Last Modified:

Flushing text file of # of records

I have a text file on the server which X number of records. I would only like to keep the first 600 records and delete the rest. The file is set up one record per line.  How do I open, read, and flush the records in that file.  Preferably at the time when a new record is submitted.
1 Solution
Since this is on the perl board, I'll answer in perl.  These should all do what you want.  All of these assume the filename (including path if not in current directory) is in $file.

# simplest, but does a system which is inefficient
system "mv $file /tmp/trunc.$$; head -600 /tmp/trunc.$$ > $file; rm /tmp/trunc.$$";

use File::Copy qw(mv);
mv $file, "/tmp/trunc.$$" or die $!;
open IN, "/tmp/trunc.$$" or die $!;
open OUT, ">$file" or die $!;
while (<IN>) {
     print OUT;
     last if ($. == 600);
close OUT;
close IN;

use Fcntl qw(O_RDWR O_EXLOCK);
use Tie::File;
# open file for reading and writing with an exclusive lock
tie @file, 'Tie::File', $file, mode => O_RDWR|O_EXLOCK or die $!;
# remove lines after 600
splice @file, 600;
untie @file;
So, are you adding records at the beginning of the file? It makes a difference whether you want to chop lines off the end of the file or off the front.

Wilcoxon's Tie::File solution can be adapated to either, and can be used for inserting the record as well. You just need to make sure you're not throwing away the most recently added record when you trim the file.

Featured Post

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now