PERL Script To Find How Many Seconds Back Was A File Updated
Submitted by Vyoma on Thu, 03/20/2008 - 13:52.
A lot of times in Unix, you would want to find out how many seconds (or minutes, or hours) back a particular file was updated. You would want to do it for several reasons - find out the last time some configuration file was changed, or may to track some update done by a different system, or anything that fancies your mind.
Though the script can be written as a Unix shell script, I found it a bit cumbersome. Moreover, the PERL solution was much more flexible, elegant and readable.
So, here is the PERL script that calculates the time period between the modified date of a file, and the system date.
#!/usr/bin/env perl use File::stat; # Declare variables my $filename; my $FILE_HANDLE; my $file_stat; my $current_time; my $diff_seconds; $filename = '/path/of/file/filename.ext'; # Open the file open ($FILE_HANDLE, $filename) or die "Can't open $filename!"; # Get the file status structure $file_stat = stat($FILE_HANDLE); # Get the current time $current_time = time; # Get the elapsed time in seconds $diff_seconds = time - $file_stat->mtime; # Do whatever you want with the $diff_seconds print "\n$filename was modified $diff_seconds seconds back.\n"; # All done
Note:
- Instead of the $file_stat->mtime, you can use $file_stat->ctime to get the time from creation of the file.
- To get the elapsed time in minutes, divide $diff_seconds by 60. For hours, divide by 3600. And so on.
Trackback URL for this post:
http://kmaheshbhat.com/trackback/167
Hi Mahesh, I have a file,after i do edit and save the file,the modified date of that file is not getting updated. On save of this file a perl script is running. So i need to add a perl script to update the modified date of a file. Since i am new to perl script i am not getting how to go ahead. I tried with touch command,but it is not working. Can u please help me
- reply
Submitted by Jayaprakash (not verified) on Thu, 05/15/2008 - 06:03.Jayaprakash, you should be able to use the utime().
To set the modified (and accessed) timestamp of a file, I would do something like this:
'/path/of/file/filename.ext');- reply
Submitted by Vyoma on Thu, 05/15/2008 - 19:28.I tried to use the set of commands that u had posted..but does not seem to be working.
My test_perl.pl file consists of
$current_time=time;
utime($current_time,$current_time,/filepath/filename.ext);
When i ran this script on command prompt
i got the following error
test_perl.pl: =: not found
test_perl.pl: syntax error at line 2: `utime' unexpected
- reply
Submitted by Jayaprakash (not verified) on Tue, 05/20/2008 - 09:31.Try giving a 'which perl' and 'perl -version' on the command line to ensure that there is PERL present.
After that, ensure that the Shebang is present in the test_perl.pl.
From the looks of it, it seems like it is running it as a shell script and not running it through PERL.
- reply
Submitted by Vyoma on Tue, 05/20/2008 - 19:38.