Perl一线式,将文件名打印为输出的一部分 [英] Perl one-liner, printing filename as part of output
问题描述
我发布了问题一个月左右的时间,关于如何打印文件列表以及这些文件中所有出现的正则表达式.目的是获得这样的文件:
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
,依此类推.
在Miller和anttix的帮助下(再次感谢!),该表达式结束了:
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
我环顾四周,没有运气想出如何以单线方式做到这一点.许多示例涉及带有 opendir
和变量等的完整Perl程序;但是作为一个20年来没有写Perl的人,我正在努力做到简约.
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.
我尝试添加 $ ARGV [9]
, @ARGV [9]
和类似的文件,但没有一个完成这项工作.
I attempted to add $ARGV[9]
, @ARGV[9]
and similar but none of them did the job.
有什么建议可以尝试吗?
Any suggestions on what to try?
推荐答案
假设您真的想坚持使用一根衬纸,并且想要修改时间
,请尝试以下操作:
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)' *
这将导入 Time :: localtime 模块.从该模块中,使用 ctime()
转换(stat文件名)[9]
的结果(修改时间
是该模块中的第9个元素 stat())从Unix时间戳返回的数组,格式更加可读.
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.
另一个变体是使用 POSIX 中的 strftime()
>模块:
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)' *
这篇关于Perl一线式,将文件名打印为输出的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!