Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the names of the first n files without listing all of them in linux

Tags:

linux

shell

unix

I know it is possible to list the first n files in a directory by simply typing: ls | head -n where n is the number of files to be listed. However the problem is the directory I'm trying to run this at is full with thousands of files causing this action to be very slow (takes a couple of minutes) while all I wanted was just the names of the first files.

Is there any way of achieving the desired behavior? and how?

like image 253
user2773143 Avatar asked Oct 17 '25 04:10

user2773143


1 Answers

If you don't mind about the ordering of the files..

You need to call the underlying libc opendir/readdir functions as this perl example shows

#!/usr/bin/perl

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

or as a oneliner, which you could call from a shell script

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

ls -l |head gives files in alphabetic order though which this cannot do. All the files have to be read to get alphabetic ordering

like image 70
Vorsprung Avatar answered Oct 18 '25 21:10

Vorsprung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!