How to find/cut for only the filename from an output of ls -lrt in Perl

。_饼干妹妹 提交于 2019-12-23 06:16:18

问题


I want the file name from the output of ls -lrt, but I am unable to find a file name. I used the command below, but it doesn't work.

$cmd=' -rw-r--r-- 1 admin u19530 3506 Aug  7 03:34 sla.20120807033424.log';
my $result=`cut -d, -f9 $cmd`;
print "The file name is $result\n";

The result is blank. I need the file name as sla.20120807033424.log


So far, I have tried the below code, and it works for the filename.

Code

#!/usr/bin/perl
my $dir = <dir path>;
opendir (my $DH, $dir) or die "Error opening $dir: $!";
my %files = map { $_ => (stat("$dir/$_"))[9] } grep(! /^\.\.?$/, readdir($DH));
closedir($DH);
my @sorted_files = sort { $files{$b} <=> $files{$a} } (keys %files);
print "the file is $sorted_files[0] \n";

回答1:


You're making it harder for yourself by using -l. This will do what you want

print((`ls -brt`)[0]);

But it is generally better to avoid shelling out unless Perl can't provide what you need, and this can be done easily

print "$_\n" for (sort { -M $a <=> -M $b } glob "*")[0];



回答2:


use File::Find::Rule qw( );
use File::stat       qw( stat );
use List::Util       qw( reduce );

my ($oldest) =
   map $_ ? $_->[0] : undef,                              # 4. Get rid of stat data.
   reduce { $a->[1]->mtime < $b->[1]->mtime ? $a : $b }   # 3. Find one with oldest mtime.
   map [ $_, scalar(stat($_)) ],                          # 2. stat each file.
   File::Find::Rule                                       # 1. Find relevant files.
      ->maxdepth(1)                                       #       Don't recurse.
      ->file                                              #       Just plain files.
      ->in('.');                                          #       In whatever dir.
  • File::Find::Rule
  • File::stat
  • List::Util



回答3:


It's not possible to do it reliably with -lrt - if you were willing to choose other options you could do it.

BTW you can still sort by reverse time with -rt even without the -l.

Also if you must use ls, you should probably use -b.




回答4:


my $cmd = ' -rw-r--r-- 1 admin u19530 3506 Aug  7 03:34 sla.20120807033424.log';

$cmd =~ / ( \S+) $/x or die "can't find filename in string " ;
my $filename = $1 ;

print $filename ; 

Disclaimer - this won't work if filename has spaces and probably under other circumstances. The OP will know the naming conventions of the files concerned. I agree there are more robust ways not using ls -lrt.




回答5:


Maybe as this:

ls -lrt *.log | perl -lane 'print $F[-1]'


来源:https://stackoverflow.com/questions/11840171/how-to-find-cut-for-only-the-filename-from-an-output-of-ls-lrt-in-perl

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