Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter filenames by pattern

Tags:

grep

perl

readdir

I need to search for files in a directory that begin with a particular pattern, say "abc". I also need to eliminate all the files in the result that end with ".xh". I am not sure how to go about doing it in Perl.

I have something like this:

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

I also need to eliminate all files from result that end with ".xh"

Thanks, Bi

like image 774
Bi. Avatar asked Jun 11 '09 21:06

Bi.


3 Answers

try

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

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

like image 82
Alex Brown Avatar answered Oct 12 '22 23:10

Alex Brown


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

You are confusing a regex 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;
like image 37
Sinan Ünür Avatar answered Oct 13 '22 00:10

Sinan Ünür


opendir(MYDIR, $newpath) or die "$!";
my @files = grep{ !/\.xh$/ && /abc/ } readdir(MYDIR);
close MYDIR;
foreach (@files) { 
   do something
}
like image 27
user118435 Avatar answered Oct 13 '22 01:10

user118435