如何在给定路径中找到没有其他子文件夹的所有文件夹?它们可能包含文件但不包含其他文件夹.
例如,给定以下目录结构:
time/aa/
time/aa/bb
time/aa/bb/something/*
time/aa/bc
time/aa/bc/anything/*
time/aa/bc/everything/*
time/ab/
time/ab/cc
time/ab/cc/here/*
time/ab/cc/there/*
time/ab/cd
time/ab/cd/everywhere/*
time/ac/
Run Code Online (Sandbox Code Playgroud)
输出find(time)应如下:
time/aa/bb/something/*
time/aa/bc/anything/*
time/aa/bc/everything/*
time/ab/cc/here/*
time/ab/cc/there/*
time/ab/cd/everywhere/*
Run Code Online (Sandbox Code Playgroud)
* 上面代表文件.
无论何时编写目录漫游器,都要使用标准的File :: Find模块.在处理文件系统时,你必须能够处理奇数角落情况,并且天真的实现很少.
提供给回调的环境(wanted在文档中命名)有三个变量,这些变量对于您想要执行的操作特别有用.
$File::Find::dir是当前目录名称
$_是该目录中的当前文件名
$File::Find::name是文件的完整路径名
当我们找到一个不是.或的目录时..,我们记录完整路径并删除它的父节点,我们现在知道它不能是叶子目录.最后,任何记录的路径都必须是叶子,因为find在File :: Find中执行深度优先搜索.
#! /usr/bin/env perl
use strict;
use warnings;
use File::Find;
@ARGV = (".") unless @ARGV;
my %dirs;
sub wanted {
return unless -d && !/^\.\.?\z/;
++$dirs{$File::Find::name};
delete $dirs{$File::Find::dir};
}
find \&wanted, @ARGV;
print "$_\n" for sort keys %dirs;
Run Code Online (Sandbox Code Playgroud)
您可以在当前目录的子目录中运行它
$ leaf-dirs time time/aa/bb/something time/aa/bc/anything time/aa/bc/everything time/ab/cc/here time/ab/cc/there time/ab/cd/everywhere
或使用完整路径
$ leaf-dirs /tmp/time /tmp/time/aa/bb/something /tmp/time/aa/bc/anything /tmp/time/aa/bc/everything /tmp/time/ab/cc/here /tmp/time/ab/cc/there /tmp/time/ab/cd/everywhere
或在同一个调用中检测多个目录.
$ mkdir -p /tmp/foo/bar/baz/quux $ leaf-dirs /tmp/time /tmp/foo /tmp/foo/bar/baz/quux /tmp/time/aa/bb/something /tmp/time/aa/bc/anything /tmp/time/aa/bc/everything /tmp/time/ab/cc/here /tmp/time/ab/cc/there /tmp/time/ab/cd/everywhere