Sara has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I am trying to grep for all files with .txt file under a directory , knowing that directory my contain subdirectories , then when I find them , I want to get one of upper directory .. forexample I will always get a resut of :
ngbb/someName/bld/one.txt ngbb/someName/bld/two.txt
I want to know the "someName" and set it to a value.
system("find /clear/pp_00/ngbb/ -name '*.txt' > CCfiles"); open (OUT , "CCfiles" ) or die " can't open CCfiles\n"; while (<OUT>) { $_ =~ m/^//\w+////; print "the someName dir is $_\n"; }

Replies are listed 'Best First'.
Re: path greping
by talexb (Chancellor) on Aug 29, 2002 at 21:19 UTC
    I must see this kind of question every week. Why try to be infinitely clever using a regular expression? Just let split do the work.
    system("find /clear/pp_00/ngbb/ -name '*.txt' > CCfiles"); open (OUT , "CCfiles" ) or die " can't open CCfiles\n"; while (<OUT>) { # Original code # $_ =~ m/^//\w+////; # print "the someName dir is $_\n"; my @Result = split ( /\//, $_ ); print "the someName dir is $Result[1]\n"; }
    No doubt there will also be Monks suggesting you use the File::Find module instead -- it's a cleaner solution to running a command through system() to get the directory scan results you want.

    --t. alex
    but my friends call me T.

    Update: My 300th node! Thanks everyone!!

      For a more OS independant solution than split I explain a way to use File::Basename in this node

      grep
      Mynd you, mønk bites Kan be pretti nasti...
Re: path greping
by ryddler (Monk) on Aug 29, 2002 at 22:10 UTC
    Sure enough talexb, here's a File::Find version :)
    use File::Find; find(\&wanted, '/clear/pp_00/ngbb'); sub wanted { next unless m|\.txt\z|is; if ($File::Find::name =~ m|/clear/pp_00/ngbb/([^/\\]+?)[/\\].*|) { print "the someName dir is $1\n"; } }
    Update: As Arien pointed out, my regex was a bit off in matching .txt extensions, and just in case a file came in as .TXT I added the 'i' after the regex as well

    ryddler
      next unless m|^.*.txt\z|s;

      According to this regex a filename without extension with at least 4 characters ending in txt matches. To match .txt files:

      next unless /\.txt\z/s;

      To find out the directory your are looking at, use $File::Find::dir.

      — Arien