Filter file names by pattern

I need to search for files in a directory starting with a specific pattern, for example "abc". I must also eliminate all files resulting in ".xh" as a result. I am not sure how to do this in Perl.

I have something like this:

opendir(MYDIR, $newpath); my @files = grep(/abc\*.*/,readdir(MYDIR)); # DOES NOT WORK 

I also need to delete all files from the result ending in ".xh"

Thanks Bi

+7
grep perl readdir
source share
6 answers

to try

 @files = grep {!/\.xh$/} <$MYDIR/abc*>; 

where MYDIR is a string containing the path to your directory.

+7
source share

opendir (MYDIR, $ newpath); my @files = grep (/ abc *. * /, readdir (MYDIR)); #DOES NOT WORK

You are mixing a regular expression pattern with a glob pattern.

 #!/usr/bin/perl use strict; use warnings; opendir my $dir_h, '.' or die "Cannot open directory: $!"; my @files = grep { /abc/ and not /\.xh$/ } readdir $dir_h; closedir $dir_h; print "$_\n" for @files; 
+7
source share
 opendir(MYDIR, $newpath) or die "$!"; my @files = grep{ !/\.xh$/ && /abc/ } readdir(MYDIR); close MYDIR; foreach (@files) { do something } 
+3
source share

That kevinadc and Sinan Unur use, but does not mention, that readdir() returns a list of all the entries in the directory when called in a list context. Then you can use any list operator. This is why you can use:

 my @files = grep (/abc/ && !/\.xh$/), readdir MYDIR; 

So:

 readdir MYDIR 

returns a list of all files in MYDIR.

and

 grep (/abc/ && !/\.xh$/) 

returns all items returned by readdir MYDIR that match the criteria there.

+2
source share
 foreach $file (@files) { my $fileN = $1 if $file =~ /([^\/]+)$/; if ($fileN =~ /\.xh$/) { unlink $file; next; } if ($fileN =~ /^abc/) { open(FILE, "<$file"); while(<FILE>) { # read through file. } } } 

You can also access all the files in the directory:

 $DIR = "/somedir/somepath"; foreach $file (<$DIR/*>) { # apply file checks here like above. } 

Alternatively, you can use the perl File :: find module.

-one
source share

Instead of using opendir and filtering readdir (don't forget closedir !) You can use glob instead:

 use File::Spec::Functions qw(catfile splitpath); my @files = grep !/^\.xh$/, # filter out names ending in ".xh" map +(splitpath $_)[-1], # filename only glob # perform shell-like glob expansion catfile $newpath, 'abc*'; # "$newpath/abc*" (or \ or :, depending on OS) 

If you don't care about $newpath with the glob prefix, get rid of map+ splitpath .

-one
source share

All Articles