linux - Unix - List all directories and subdirectories, excluding directories without files
2014-07
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 follwing 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 yust 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 adive of how to filter directories which contain no files (only subdirectories).
Thanks in advance
ftiaronsem
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
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
...
Suppose you are in a directory that contains many files and many subdirectories.
You want to get a directory listing of all the files beginning with the letter "d". You type
ls d*
and what you get back is mostly files in sub-directories (in particular, files in subdirectories that begin with "d").
How do you list only the files and directory names in your current directory?
Ah, I just found it on the 6th reading of the man page. It's the not-so-sensibly named "directory" parameter
ls -d d*
I believe another interesting solution to be,
ls | grep ^d
Offers the flexibility of regular expressions.
find . -maxdepth 1 -name d* -type f
Okay, using find here is a tad of overkill. Just a tad.
ls -ld
: It will give the list of directories, without descending into subdirectories.
Example:
ls -ld Cust*
This command will provide a listing of the files and directories which start with Cust
.