List all directories and subdirectories, excluding directories without files

2

2

I would like to list all the directories and sub directories in and below the current path. Since I only wanted to display directories I came up with the following command:

find -type d -exec ls -d1 {} \; | cut -c 3-

This prints out for example

webphone
music
finance
finance/banking
finance/realestate
finance/trading
finance/other
finance/moneylending
finance/insurance
webradio
webtv

The problem I have right now is, that the directory finance is listed. finance contains no files, just the sub directories you see above. What I want to achieve is the following output:

webphone
music
finance/banking
finance/realestate
finance/trading
finance/other
finance/moneylending
finance/insurance
webradio
webtv

In this list the directory finance is not listed. Therefore I need your advice of how to filter directories which contain no files (only subdirectories).

ftiaronsem

Posted 2010-10-16T10:00:06.870

Reputation: 503

why are you using find -type d -exec ls -d1 {} \; instead of ls -d1 */? – phuclv – 2020-01-17T07:24:42.700

Answers

5

Here's one way: list all regular files, strip away the file basenames, and remove duplicates.

find . -type f | sed 's!/[^/]*$!!' | sort -u

If you want to strip the leading ./:

find . -type f | sed -e 's!/[^/]*$!!' -e 's!^\./!!' | sort -u

Gilles 'SO- stop being evil'

Posted 2010-10-16T10:00:06.870

Reputation: 58 319

Thank you so much! Your reg-exp search was nearly perfect. I just had to strip the "./" and to remove the first emtpy line. The command I run now is: find . -type f | sed 's!/[^/]*$!!' | sort -u | sed '1d' | cut -c 3- – ftiaronsem – 2010-10-16T10:55:51.323

@ftiaronsem: the empty line corresponds to the current directory. See my edit. – Gilles 'SO- stop being evil' – 2010-10-16T11:19:35.287

2

I consider installing tree:

  • sudo apt-get install tree

and then run

  • tree -d /path/to/start/dir

to display directories only.

Example:

root@X100e:~# tree -d /var/cache/
/var/cache/
├── apache2
│   └── mod_disk_cache
├── apt
│   └── archives
│       └── partial
├── binfmts
├── cups
│   └── rss
├── debconf
├── dictionaries-common
├── flashplugin-installer
...

udo

Posted 2010-10-16T10:00:06.870

Reputation: 7 661

0

find has an -empty option that you can use directly

find . -type d ! -empty

phuclv

Posted 2010-10-16T10:00:06.870

Reputation: 14 930

But this will show directories that have subdirectories but don’t contain any files — and the OP wants these to be treated as empty.  Also, please don’t teach people to use -not without at least mentioning the original (and POSIX-compliant) “not” operator, namely !. – Scott – 2020-01-17T07:05:37.890