简体   繁体   中英

How can I filter filenames based on their extension?

The following script stores all the files and directories in the array @file_list .

How do I only filter only files with the .lt6 extension and none other than that?

opendir (CURRDIR, $localdir);
@file_list = grep !/^\.\.?$/, readdir CURRDIR;
print STDOUT "Found Files: @file_list\n";

cheers

Try this:

grep(/\.lt6$/i, readdir(CURRDIR))

I've used it many times. It works, although now I prefer to use File::Next for this sort of thing.

Example:

use File::Next;

my $iter = File::Next::files( { file_filter => sub { /\.lt6$/ } }, $localdir )

while ( defined ( my $file = $iter->() ) ) {
    print $file, "\n";
}

Don't forget to closedir() .

Your grep should look for:

my(@file_list) = grep /\.lt6$/, readdir CURRDIR;

Assuming the rest of your syntax is approximately correct.

You can use File::Find::Rule ;

use File::Find::Rule;

print "FOUND:\n    "
    , join( "\n    "
          , File::Find::Rule->file->name( '*.lt6' )->in( $path )
          )
    , "\n"
    ;
my @file_list = glob "$localdir/*.lt6";
opendir (CURRDIR, $localdir);
@file_list = grep m/\.lt6$/, readdir CURRDIR;
closedir CURRDIR;
print STDOUT "Found Files: @file_list\n";

And to add a little variety, you can also do stuff like this:

opendir(DIR, $path) || die qq([ERROR] Cannot opendir "$path" - $!\n);
my(@txt) = grep(m{\.txt$}, readdir DIR);
rewinddir DIR;
my(@lt6) = grep(m{\.lt6$}, readdir DIR);
rewinddir DIR;
my(@dirs) = grep(-d "$path/$_", readdir DIR);
closedir DIR;

And so on.

Go to the command prompt

cd \\

dir /s *.lt6 > mydir.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM