in reply to How do I find directories within directories using : parse_dir(`ls -l`)
It's obvious that the directory entries start with a "d" as the first character on the line. So, we parse the lines looking for a "d" at the beginning of the line. Then we parse those lines with split. Notice that I limit split to 10 columns because the directory name might have spaces in it. I call split in list context and only grab the 10th entry (the directory name) since you didn't ask for the other stuff. Note that this will miss symlinks and I caution once again to use readdir.-rwxr-xr-x 1 rhettbull Domain U 294 Aug 31 10:59 dirs.pl drwxr-xr-x 2 rhettbull Domain U 0 Aug 31 10:58 testdir
#!/bin/perl use strict; use warnings; my $lookhere = shift || '.'; parse_dir($lookhere); sub parse_dir { my $rootdir = shift || '.'; my @listing = `ls -l $rootdir`; foreach (@listing) { chomp; if (/^d/) { my $dir = (split /\s+/, $_, 10)[9]; print "$dir\n"; } } }
Originally posted as a Categorized Answer.
|
|---|