iDev
iDev

Reputation: 2433

How to check if a file with a .txt extension exists in a directory?

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

Answers (3)

Zaid
Zaid

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

cas
cas

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

Orabîg
Orabîg

Reputation: 12002

Simply using glob :

if ( <*.txt> ) { ... }

Upvotes: 4

Related Questions