如何在Perl中仅从ls -lrt的输出中查找/剪切文件名 [英] How to find/cut for only the filename from an output of ls -lrt in Perl

查看:125
本文介绍了如何在Perl中仅从ls -lrt的输出中查找/剪切文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要从 ls -lrt 的输出中获取文件名,但是找不到文件名。我使用了下面的命令,但是它不起作用。

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";

结果为空白。我需要文件名为 sla.20120807033424.log

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.

#!/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";


推荐答案

使用 -l <​​/ code>。这会做你想要的

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

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

但是通常最好避免炮轰,除非Perl无法提供所需的东西,而这可以很容易地完成

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];

这篇关于如何在Perl中仅从ls -lrt的输出中查找/剪切文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆