I have a directory containing multiple subdirectories. I want to list only those subdirectories that contain at least one file. How can I do that?
Use the 'find' command along with the '-type' flag that specifies the directory type search using the keyword 'd'. The word '-empty' has been used as a flag to search only empty directories within the home directory as stated below. The dot means the current location which is the home directory of a Linux-based system.
Type the ls -l command to list the contents of the directory in a table format with columns including: content permissions.
Find all (non-)empty files in a directory By default, the find command excludes symbolic files. Use the -L option to include them. The expression -maxdepth 1 specifies that the maximum depth to which the search will drill is one only. By default, the find command will recursively go down the directory.
If you name one or more directories on the command line, ls will list each one. The -R (uppercase R) option lists all subdirectories, recursively. That shows you the whole directory tree starting at the current directory (or the directories you name on the command line).
find . -mindepth 1 -maxdepth 1 -not -empty -type d
will give you all nonempty directories. If you want to exclude directories that contain only other directories (but no files), one of the other answers might be better...
find . -type f -print0 | xargs -0 -n 1 dirname | sort -u
How about:
find /nominated/directory -type f |
sed 's%/[^/]*$%% |
sort -u
Find files - drop file name part - sort uniquely.
It won't list subdirectories that contain only other sub-sub-directories.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With