[英]Shell script to list all subdirectories recursively within a folder that contains files with an specific extension
I have a folder named a, and it may have one or multiple sub-directories and the sub-directories may have multiple sub-directories and so on. 我有一个名为a的文件夹,它可能有一个或多个子目录,并且这些子目录可能有多个子目录,依此类推。 I want to know how can I write a shell script to list all the sub-directories that contain a file with specific extension.
我想知道如何编写Shell脚本以列出包含带有特定扩展名的文件的所有子目录。
So, it may be like 所以,可能就像
A -> B -> C
-> D -> f2.txt
-> F -> f3.txt
-> E -> G -> H -> f4.txt
So only D, F and H directories will be listed. 因此,仅列出D,F和H目录。 Actually I need this as a quick way to find the package names of particular java classes, by listing their directory tree.
实际上,我需要通过列出它们的目录树来作为查找特定Java类的包名称的快速方法。 For example in the previous example AEGH is a package same as AD, but AEG is not a package as G only contains a sub directory H no files.
例如,在前面的示例中,AEGH是与AD相同的软件包,但AEG不是软件包,因为G仅包含子目录H,没有文件。
I think you need find
command. 我认为您需要
find
命令。 You can use like this, 你可以这样使用
find . -name '*.txt'
Here, 这里,
.
- dot( .
) is current directory. -dot(
.
)是当前目录。 You can also specify the path where to start. 您还可以指定从哪里开始的路径。
-name
- file name to find. -name
要查找的文件名。
You can also use -maxdepth
option to limit the depth of recursive finding. 您也可以使用
-maxdepth
选项限制递归查找的深度。 Normally, find
will find the file recursively. 通常,
find
将以递归方式找到文件。
Update: 更新:
If you want to list out the directories, 如果您要列出目录,
find . -name '*.txt' -exec dirname {} \;
find . -name '*.txt' -printf '%h\\n'
man find
将给出与-printf
使用的其他可能的格式标志
A simpler and faster alternative for systems like MAC. 对于MAC这样的系统,更简单,更快速的替代方法。 No need to use 2 additional tools and even repeatingly call
dirname
: 无需使用2个其他工具,甚至无需重复调用
dirname
:
find -type f -name '*.txt' | awk 'BEGIN{FS=OFS="/"}{--NF}!a[$0]++'
-type f
may be removed optionally if it doesn't work. 如果
-type f
无效,则可以将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.