Reputation: 2433
I want to know how to check if a directory has a file with .txt
extension in it.
How can it be done?
Upvotes: 1
Views: 4667
Reputation: 37146
Remember that *.txt
could actually be a directory. If it is files you are after, grep
the glob
:
if ( grep -f, glob '*.txt' ) { ... }
Upvotes: 0
Reputation: 735
#! /usr/bin/perl
my $dir = '.'; # current dir
opendir(DIRHANDLE, $dir) || die "Couldn't open directory $dir: $!\n";
my @txt = grep { /\.txt$/ && -f "$dir/$_" } readdir DIRHANDLE;
closedir DIRHANDLE;
print ".txt files found" if (scalar(@txt));
As a bonus, all .txt files found are in array @txt.
Upvotes: 0