gpt4 book ai didi

linux - 获取前 n 个文件的名称而不在 linux 中列出所有文件

转载 作者:太空狗 更新时间:2023-10-29 12:16:35 28 4
gpt4 key购买 nike

我知道只需键入以下内容就可以列出目录中的前 n 个文件:ls | head -n 其中 n 是要列出的文件数。然而,问题是我试图运行它的目录充满了数千个文件,导致这个操作非常慢(需要几分钟),而我想要的只是第一个文件的名称。

是否有任何方法可以实现所需的行为?如何?

最佳答案

如果您不介意文件的顺序..

您需要调用底层 libc opendir/readdir 函数,如此 perl 示例所示

#!/usr/bin/perl

opendir(my $dh, ".") || die "can't opendir . : $!";
for (1..10) {
$filename=readdir($dh);
print "$filename\n";
}

或者作为一个 oneliner,您可以从 shell 脚本中调用

perl -le 'opendir($d, "."); print scalar readdir($d) for (1..10);'

ls -l |head 按字母顺序给出文件,但这是做不到的。必须读取所有文件才能按字母顺序排序

关于linux - 获取前 n 个文件的名称而不在 linux 中列出所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22742023/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com