1

Given an output like this:

-rw-r--r--   1 tinosino  staff   4.0K 21 Mar  2012 EtcHosts_Backup_2012-03-21_21-19-10.txt
-rw-r--r--   1 tinosino  staff   3.8K  1 Apr  2012 EtcHosts_Backup_2012-04-01_01-06-12.txt
-rw-r--r--   1 tinosino  staff   3.9K 18 Jun  2012 EtcHosts_Backup_2012-06-18_18-33-40.txt
-rw-r--r--   1 tinosino  staff   3.9K 27 Aug  2012 EtcHosts_Backup_2012-08-27_09-37-44.txt

I'd like to get the last field (the filename) of the last line (27 Aug), basically:

EtcHosts_Backup_2012-08-27_09-37-44.txt

I am interested in how to best do this in perl.

If there is a better way to do this with just ls, it is not what I am looking for (I know I can sort by date, creation, modification, etc. and I can -1t to just show the filename)

This is essentially about learning how to do in perl what I generally do in awk:

ll | tail -n 1 | awk '{print $NF}'

giving:

EtcHosts_Backup_2012-08-27_09-37-44.txt

Which is "the desired answer".

Here my attempt:

ll | perl -lane 'eof() && print $F[$#F]'

Could I improve on this ugly-looking piece of.. F? $F[$#F]

The answer "seems right", yet the way to get $NF seems primordial.

4

2 回答 2

1

Improvement:

perl -lane 'eof() && print $F[-1]'  # or ...
perl -lane 'eof() && print pop @F'

Further:

perl -lane 'END { print $F[-1] }'   # or...
perl -lane 'END { print pop @F }'

and of course, why not just:

ls | tail -1
于 2013-03-31T03:09:33.163 回答
1

To answer your specific question about improving on $F[$#F], Perl supports using negative numbers as array indices. For example, -1 refers to the last element of the list, so you could write your one-liner as:

ll | perl -lane 'eof() && print $F[-1]'
于 2013-03-31T03:12:55.403 回答