How to count files or directories

For this example I will use such tree:

.
├── dir1/
│   ├── dir6/
│   ├── dir7/
│   ├── dir8/
│   ├── file4
│   └── file5
├── dir2/
│   └── dir9/
│       ├── dir10/
│       │   ├── file9
│       │   └── file10
│       ├── file6
│       ├── file7
│       └── file8
├── dir3/
├── dir4/
├── dir5/
├── file1
├── file2
└── file3

List of all files and directories:

$ find . | sort | grep -v ^.$
./dir1
./dir1/dir6
./dir1/dir7
./dir1/dir8
./dir1/file4
./dir1/file5
./dir2
./dir2/dir9
./dir2/dir9/dir10
./dir2/dir9/dir10/file9
./dir2/dir9/dir10/file10
./dir2/dir9/file6
./dir2/dir9/file7
./dir2/dir9/file8
./dir3
./dir4
./dir5
./file1
./file2
./file3

Number of all files and directories:

$ find . | grep -v ^.$ | wc -l
20

List of all directories:

$ find . -type d | grep -v ^.$
./dir3
./dir5
./dir1
./dir1/dir6
./dir1/dir8
./dir1/dir7
./dir2
./dir2/dir9
./dir2/dir9/dir10
./dir4

Count of all directories:

$ find . -type d | grep -v ^.$ |wc -l
10

List of subdirectories in current directory:

$ find . -maxdepth 1 -type d | sort | grep -v ^.$
./dir1
./dir2
./dir3
./dir4
./dir5

Count of subdirectories in current directory:

$ find . -maxdepth 1 -type d | grep -v ^.$ | wc -l
5

List of all files:

$ find . -type f | sort
./dir1/file4
./dir1/file5
./dir2/dir9/dir10/file9
./dir2/dir9/dir10/file10
./dir2/dir9/file6
./dir2/dir9/file7
./dir2/dir9/file8
./file1
./file2
./file3

Count of all files:

$ find . -type f | wc -l
10

List of files only in current directory:

$ find . -maxdepth 1 -type f | sort
./file1
./file2
./file3

Count of files only in current directory:

$ find . -maxdepth 1 -type f | wc -l
3
Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.

Gdansk, Poland https://sleeplessbeastie.eu