简体   繁体   中英

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. I want to know how can I write a shell script to list all the sub-directories that contain a file with specific extension.

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. Actually I need this as a quick way to find the package names of particular java classes, by listing their directory tree. 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.

I think you need find command. You can use like this,

find . -name '*.txt'

Here,

. - dot( . ) is current directory. You can also specify the path where to start.

-name - file name to find.

You can also use -maxdepth option to limit the depth of recursive finding. Normally, find will find the file recursively.

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. No need to use 2 additional tools and even repeatingly call dirname :

find -type f -name '*.txt' | awk 'BEGIN{FS=OFS="/"}{--NF}!a[$0]++'

-type f may be removed optionally if it doesn't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM