user
Task

Walk a given directory *tree* and print files matching a given pattern.

**Note:** This task is for recursive methods.   These tasks should read an entire directory tree, not a *single directory*.

**Note:** Please be careful when running any code examples found here.

Related task

* Walk a directory/Non-recursively   (read a *single directory*).
assistant
(formerly Perl 6)

Using the File::Find module:

```
use File::Find;

.say for find dir => '.', name => /'.txt' $/;

```

Alternatively, a custom solution that provides the same interface as the built-in (non-recursive) dir function, and uses gather/take to return a lazy sequence:

```
sub find-files ($dir, Mu :$test) {
    gather for dir $dir -> $path {
        if $path.basename ~~ $test { take $path }
        if $path.d                 { .take for find-files $path, :$test };
    }
}
 
.put for find-files '.', test => /'.txt' $/;

```

Or if you value performance over portability, here's a function that runs the GNU find program and returns a lazy sequence of the files it finds. Parameters are not subjected to shell expansion, and the null-byte (which cannot be present in file paths) is used as the path delimiter, so it should be pretty safe.

```
sub find-files ($dir, :$pattern) {
    run('find', $dir, '-iname', $pattern, '-print0', :out, :nl«\0»).out.lines;
}

.say for find-files '.', pattern => '*.txt';

```