Reputation: 67
I have a piece of code in Perl to grep for files with specific names under a directory.
push @{ $output{archives} }, grep {-f $_} "$output{dir}/result0.txt”, "$output{dir}/outcome.txt”;
say "@{ $output{archives} } \n";
This will search for files of names result0.txt
, outcome.txt
under the directory $output{dir}
. These results will be pushed into the array $output{archives}
.
How can I search for file names of pattern outcome_0.txt
, outcome_1.txt
, outcome_2.txt
, etc. and push to the array?
I tried changing "$output{dir}/outcome.txt”
to "$output{dir}/outcome*.txt”
, but it is not giving any results at all.
Upvotes: 0
Views: 163
Reputation: 40748
If you want find files matching outcome_*.txt
you can use the glob
function or aka <>
:
push @{ $output{archives} }, grep {-f $_} <"$output{dir}/outcome_*.txt">;
or, using glob
instead of <>
:
push @{ $output{archives} }, grep {-f $_} glob "$output{dir}/outcome_*.txt";
or using a more specific regexp:
push @{ $output{archives} }, grep {(-f $_) && /outcome_\d+\.txt$/} glob "$output{dir}/*";
From perldoc glob :
glob
In list context, returns a (possibly empty) list of filename expansions on the value of EXPR such as the standard Unix shell /bin/csh would do. In scalar context, glob iterates through such filename expansions, returning undef when the list is exhausted.
See perldoc glob and perldoc perlop for more information.
Upvotes: 2