Reputation: 1357
Hi all I was wondering how I can go about searching for files in perl.
Right now I have a line with information that I have tokenized with tab as a delimiter stored into an array. (using split) These arrays contain stub text of filenames I want to search for in a directory. For example Engineering_4.txt would just be "Engin" in my array.
If there are two different files... Engineering_4 and Engineering_5, it would search both these files for content and just extract the information I need from one of them (only 1 contains information I want). I would imagine my script will have to search and store all file names that match and then search through each of these files.
My question is how do I go about searching for files in a directory matching a regular expression in Perl? Also is there a way to limit the file types that I want to search for. For example, I just want to only search for ".txt" files.
Thanks everyone
Upvotes: 2
Views: 10815
Reputation: 7516
You can also use the File::Find module:
#!/usr/bin/env perl
use strict;
use warnings;
use File::Find;
my @dirs = @ARGV ? @ARGV : ('.');
my @list;
find( sub{
push @list, $File::Find::name if -f $_ && $_ =~ m/.+\.txt/ },
@dirs );
print "$_\n" for @list;
Upvotes: 0
Reputation: 37146
The glob
function returns an array of matching files when provided a wildcard expression.
This means that the files can also be sort
-ed before processing:
use Sort::Key::Natural 'natsort';
foreach my $file ( natsort glob "*.txt" ) { # Will loop over only txt files
open my $fh, '<', $file or die $!; # Open file and process
}
Upvotes: 0
Reputation: 26930
I guess since you already know the directory you could open it and read it while also filtering it :
opendir D, 'yourDirectory' or die "Could not open dir: $!\n";
my @filelist = grep(/yourRegex/i, readdir D);
Upvotes: 4