Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl finding a file based off it's extension through all subdirectories

Tags:

perl

I have a segment of code that is working that finds all of the .txt files in a given directory, but I can't get it to look in the subdirectories.

I need my script to do two things

  1. scan through a folder and all of its subdirectories for a text file
  2. print out just the last segments of its path

For example, I have a directory structed

C:\abc\def\ghi\jkl\mnop.txt

I script that points to the path C:\abc\def\. It then goes through each of the subfolders and finds mnop.txt and any other text file that is in that folder.

It then prints out ghi\jkl\mnop.txt

I am using this, but it really only prints out the file name and if the file is currently in that directory.

opendir(Dir, $location) or die "Failure Will Robertson!";
@reports = grep(/\.txt$/,readdir(Dir));
foreach $reports(@reports)
{
    my $files = "$location/$reports";
    open (res,$files) or die "could not open $files";
    print "$files\n";
}
like image 784
Heuristic Avatar asked Mar 08 '13 21:03

Heuristic


1 Answers

I do believe that this solution is more simple and easier to read. I hope it is helpful !

#!/usr/bin/perl

use File::Find::Rule;

my @files = File::Find::Rule->file()
                            ->name( '*.txt' )
                            ->in( '/path/to/my/folder/' );

for my $file (@files) {
    print "file: $file\n";
}
like image 95
Tk421 Avatar answered Sep 25 '22 21:09

Tk421