Perl one-liner, printing filename as part of output

做~自己de王妃 提交于 2021-01-28 05:52:35

问题


I posted a question a month or so ago about how to print out a listing of files and all occurrences of a regular expression in those files. The aim being to get a file like this:

    file1 A12345
    file2 A12399
    file2 A12599
    file3 A11223

and so on.

After some help from Miller and anttix (thanks again!), the expression wound up being:

    perl -lne 'print "$ARGV $1" while(/\<myxmltag>(..............)<\/myxmltag>/g)' *.XML >  /home/myuser/myfiles.txt

Now I'd really like to be able to add the file's create date (in any format), so my result would be something like this (as before: exact format, order of fields etc. does not matter):

    file1 A12345 01/01/2013
    file2 A12399 02/03/2013
    file2 A12599 02/03/2013

I've looked around and had no luck figuring out how to do this in a one-liner. Lots of examples involving full Perl programs with opendir and variables and so on; but as someone who hasn't written Perl in 20 years, I'm trying to be minimalistic.

I attempted to add $ARGV[9], @ARGV[9] and similar but none of them did the job.

Any suggestions on what to try?


回答1:


Assuming you really want to stick with a one liner and you want the modification time, try this:

perl -MTime::localtime -lne 'print "$ARGV  $1 ". ctime((stat "$ARGV" )[9]) while(/\<myxmltag>(..............)<\/myxmltag>/g)' *

This imports the Time::localtime module. From that module ctime() is used to convert the result of (stat filename)[9] (the modification time is the 9th element in the array returned by stat()) from a unix time stamp into a more readable format.

Another variant would be to use strftime() from the POSIX module:

   perl -MPOSIX -lne 'print "$ARGV $1 " . strftime("%d/%m/%y", localtime((stat "$ARGV")[9])) while(/\<myxmltag>(..............)<\/myxmltag>/g)' *


来源:https://stackoverflow.com/questions/23477621/perl-one-liner-printing-filename-as-part-of-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!