How to get file creation time in Unix with Perl

2019-06-03 08:22发布

How to get file creation time in unix with perl?

I have this command which displays file's last modification time:

perl -MPOSIX -le 'print strftime "%d %b %Y %H:%M ".$_, localtime((lstat)[9]) for @ARGV' file.txt

2条回答
Animai°情兽
2楼-- · 2019-06-03 09:06

There is not normally file creation time in UNIX. A new xstat() interface promises support for it, but perl doesn't use it. It is possible to write an XS-based interface to gain access to it.

In Perl on UNIX, ctime stands for Inode Change Time, which has nothing to do with file creation.

According to perlport, ctime will be creation time only on Windows, but you might want to use the Win32API::File::Time::GetFileTime() since it is more explicit (and will be obvious to porters) that your program depends on creation time instead of whatever ctime contains.

查看更多
闹够了就滚
3楼-- · 2019-06-03 09:09

You almost have it.

You just need to pass the return value from localtime instead of the filename to strftime:

perl -MPOSIX -e 'printf "%s %s\n", $_, strftime("%d %b %Y %H:%M", localtime((lstat)[9])) for @ARGV' file.txt

Outputs:

file.txt 10 Oct 2014 15:38

And even though it takes more code, I'd lean toward using Time::Piece and File::stat to make the code more modern and readable:

perl -MTime::Piece -MFile::stat -e '
    printf "%s %s\n",  $_, localtime( stat($_)->mtime )->strftime("%d %b %Y %H:%M") for @ARGV
  ' file.txt
查看更多
登录 后发表回答