How to find a file whose name may be longer than the intended name?

I am engaged in testing, where I have many files that I need for data analysis. We have a naming convention with our files, but sometimes someone will add a little more file name. I am looking for a way to find the "core" name and save the whole file name.

For example, I want to find WIRA_Rabcd_RT, but someone can save the file name as RED_GREEN_BLUE_WIRA_Rabcd_RT.txt, so my folder will look something like this:

RED_GREEN_BLUE_WIRB_Rabcd_RT.txt
RED_GREEN_BLUE_WIRC_Rabcd_RT.txt
RED_GREEN_BLUE_WIRA_Rabcd_RT.txt ← I want to find this file, and open it.
RED_GREEN_BLUE_WIRF_Rabcd_RT.txt
RED_GREEN_BLUE_WIRG_Rabcd_RT.txt
RED_GREEN_BLUE_WIRT_Rabcd_RT.txt
RED_GREEN_BLUE_WIRW_Rabcd_RT.txt
RED_GREEN_BLUE_WIRQ_Rabcd_RT.txt
+3
source share
2 answers

The glob function seems to do the trick:

my $dir = '/some/directory/';
my @files = glob($dir . '*WIRA_Rabcd_RT.txt');

# Make sure you get exactly one file, open it, etc.
+7
source

In Perl TIMTOWTDI, here's another way:

#!/usr/bin/perl

use strict;
use warnings;

my $dir = 'dirname';
my $pattern = 'WIRA_Rabcd_RT';

my @files;

{ 
  opendir my $dir_handle, $dir;
  @files = grep { /$pattern/ } readdir $dir_handle;
} #end-of-block autocloses lexical $dir_handle 

@files , . , ( name not dir/name). File::chdir, $dir . :

use File::chdir

# get @files in $dir as above...

{
  local $CWD = $dir;
  # work with files in @files
} 

# working directory restored to original here
0

All Articles