Search code examples
regexperldate

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

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?


Solution

  • 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)' *