命令到达树的底部

命令到达树的底部

是否有一个 Linux 命令可以返回最底层目录的文件路径。

我尝试过以下命令: find /home/Alison/workspace/DirLevel1/DirLevel2/DirLevel3/DirLevel4/DirLevel5/DirLevel6/DirLevel7/ -type d

tree -dfi /home/Alison/workspace/DirLevel1/DirLevel2/DirLevel3/DirLevel4/DirLevel5/DirLevel6/DirLevel7/

这两个命令都返回:

/home/Alison/workspace/DirLevel1/DirLevel2/DirLevel3/DirLevel4/DirLevel5/DirLevel6/DirLevel7
/home/Alison/workspace/DirLevel1/DirLevel2/DirLevel3/DirLevel4/DirLevel5/DirLevel6/DirLevel7/generic
/home/Alison/workspace/DirLevel1/DirLevel2/DirLevel3/DirLevel4/DirLevel5/DirLevel6/DirLevel7/admin
/home/Alison/workspace/DirLevel1/DirLevel2/DirLevel3/DirLevel4/DirLevel5/DirLevel6/DirLevel7/logandnetworkactivity
/home/Alison/workspace/DirLevel1/DirLevel2/DirLevel3/DirLevel4/DirLevel5/DirLevel6/DirLevel7/qvm
/home/Alison/workspace/DirLevel1/DirLevel2/DirLevel3/DirLevel4/DirLevel5/DirLevel6/DirLevel7/qvm/a
/home/Alison/workspace/DirLevel1/DirLevel2/DirLevel3/DirLevel4/DirLevel5/DirLevel6/DirLevel7/reports

正如您所见:

/home/Alison/workspace/DirLevel1/DirLevel2/DirLevel3/DirLevel4/DirLevel5/DirLevel6/DirLevel7/qvm

    /home/Alison/workspace/DirLevel1/DirLevel2/DirLevel3/DirLevel4/DirLevel5/DirLevel6/DirLevel7/qvm/a

它正在返回,/qvm/并且/qvm/a我只想要底部目录。

答案1

这应该可以完成这项工作:

find . -type d | \
  awk -F/ '
    NF <= old_NF {print prev}
    {old_NF=NF; prev=$0}
    END {print $0}
  '

例子:

find . -type d
.
./backup
./source
./source/siteA
./source/siteA/regionA
./source/siteA/regionA/files
./source/siteA/regionB
./source/siteA/regionB/files
./source/siteA/regionD
./source/siteA/regionD/files
./source/siteA/regionC
./source/siteA/regionC/files
./source/dir with space
./source/siteB
./source/siteB/regionA
./source/siteB/regionA/files
./source/siteB/regionB
./source/siteB/regionB/files

现在上面的命令给出:

./backup
./source/siteA/regionA/files
./source/siteA/regionB/files
./source/siteA/regionD/files
./source/siteA/regionC/files
./source/dir with space
./source/siteB/regionA/files
./source/siteB/regionB/files

简短解释:

纯文本find . -type d输出已经按照目录结构排序。你现在想要的是那些位于具有相同或更少深度的行之前的行(=路径)。并且最后一行(始终)。

该命令的作用如下awk。它根据路径分隔符 ( -F/) 拆分输入行,存储字段数和行 ( {old_NF=NF; prev=$0}),然后将旧字段数与当前字段数进行比较,如果字段数小于或等于 ( ),则打印存储的行NF <= old_NF {print prev}。并且它始终打印最后一行 ( END {print $0})。

相关内容