How can I filter file names based on their extension?

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

How can I only filter files with the extension .lt6 and nothing else?

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

amuses

+4
source share
7 answers

Try the following:

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

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

Example:

 use File::Next; my $iter = File::Next::files( { file_filter => sub { /\.lt6$/ } }, $localdir ) while ( defined ( my $file = $iter->() ) ) { print $file, "\n"; } 
+9
source

Do not forget closedir() .

Your grep should look for:

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

Assuming the rest of your syntax is approximately correct.

+3
source

You can use File :: Find :: Rule ;

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

And to add a little variety, you can also do things 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.

0
source

Go to command prompt

cd \

dir / s * .lt6> mydir.txt

-1
source

All Articles