Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last modified time of a file in perl in the format returned from diff command?

Tags:

I want to display time in the same format as is displayed by the linux diff command.

D:\>diff -dub old.cfg new.cfg
--- old.cfg       2019-05-15 15:03:14.289950700 +0530
+++ new.cfg       2019-05-14 16:07:21.119695300 +0530

I want to show last modified time of a file as 2019-05-15 15:03:14.289950700 +0530.
I used stat but I am not getting that nanosecond part. Alo, need timezone in given format. I tried Time::HiRes too, but couldn't get.

my $dt = strftime("%Y-%m-%d %H:%M:%S", localtime((stat($old_file))[9]));

It returns: 2019-05-15 15:03:14. Can you please help me to append the other info?

like image 700
Kamal Nayan Avatar asked May 16 '19 06:05

Kamal Nayan


People also ask

How can I tell what time a file was modified?

To see the access time for a file with ls , append the -u option in your command. In this case, our access time is the same as the file's modified time, which is normal for files that have not been accessed since they were last saved.

What is modification time in Linux?

Modified Time. The modified timestamp contains the time the file's data has been changed. It means when we make changes to the actual contents of the file, the file system will update the modification time.


1 Answers

I must first say, that's not going to be accurate. Even as your hardware likely supports nanosecond resolution by the time it gets back to software it's hundreds of times off. (With a file's timestamp, presumably used only as relative to other files, that may be less important.)

Having said that, the only way I find to claim nanoseconds is to use system's tools, so stat

my ($ts) = grep { /^\s*Access: [0-9]{4}/ } qx(stat $file);
$ts =~ s/^\s*Access:\s+//;

or, using map also as a filter

my ($ts) = map { /^\s*Access:\s+([0-9]{4}.*)/ ? $1 : () } qx(stat $file);

One problem here, of course, is that we have to parse output; so see your man pages and test your stat, and don't hope for much portability. Watch for system changes as output format of programs may change. But I don't find nanoseconds claim in Perl.

For reference, on my CentOS 7 (under both bash and tcsh)

perl -we'$f=shift; print grep { /^\s*Access: [0-9]{4}/ } qx(stat $f)' file

prints, for a random file

Access: 2019-05-15 13:21:57.723987422 -0700

Once again, the "nano"seconds aren't accurate at all.


Another option, for perhaps more reliable output parsing, is to use ls with its --full-time

my $ts = join ' ', (split ' ', qx(ls --full-time $file))[5..7];

As always, when running external commands build your variables with care and quote and escape appropriately. A good tool is String::ShellQuote. Or, better avoid the shell altogether unless it's specifically needed. Best do all this using a module for running external tools.

like image 159
zdim Avatar answered Sep 21 '22 16:09

zdim