RHEL or Centos: How to count number of files inside a directory in Linux ?

In this article, we will look different ways or tricks to count number of files inside a directory in linux.

I. Get files inside /tmp
Using “wc -l” command on long list.

### Gets count of files inside /tmp
$ ls -l /tmp/ | grep -v ^total | wc -l
       8

### Gets count of files inside /tmp + count of file/dir inside immediate dir in /tmp.
### it doesn't get all files inside this dir
$ ls -l /tmp/* | grep -v ^total | grep . |wc -l
      13

 

grep -v ^total omits the first line.
grep . gets the non-empty lines.


II. Get all files & directories count inside a directory
1. Using rsync Command

$ rsync --stats --dry-run -ax /tmp/
drwxrwxrwt         340 2019/04/02 13:01:58 .
-rw-rw-rw-           0 2019/04/02 09:57:42 opensc-tokend.log
-rw-r--r--     2004020 2019/04/02 13:00:33 wbxtra_04022019_125559.wbt
-rw-r--r--    28424740 2019/04/02 13:19:27 wbxtra_04022019_130151.wbt
drwx------         136 2019/04/02 10:00:29 .vbox-saket1447583-ipc
srwx------           0 2019/04/02 10:00:41 .vbox-saket1447583-ipc/ipcd
-rw-------           4 2019/04/02 10:00:31 .vbox-saket1447583-ipc/lock
drwx------         102 2019/04/02 09:58:33 com.ngelinux.launchd.42d7hbjJu1
srw-rw-rw-           0 2019/04/02 09:58:33 com.ngelinux.launchd.42d7hbjJu1/Listeners
drwx------         102 2019/04/02 09:58:33 com.ngelinux.launchd.Mm3rlHlt2q
srw-rw-rw-           0 2019/04/02 09:58:33 com.ngelinux.launchd.Mm3rlHlt2q/Render
drwx------         102 2019/04/02 09:58:33 com.ngelinux.launchd.sy707ym3Mu
srw-rw-rw-           0 2019/04/02 09:58:33 com.ngelinux.launchd.sy707ym3Mu/Listeners
drwx------         102 2019/04/02 12:55:53 wbxtrace
drwx------         136 2019/04/02 13:01:50 wbxtrace/gpc
-rw-r--r--      268216 2019/04/02 12:56:19 wbxtrace/gpc/wbxtra_gpc_04022019_125553.wbt
-rw-r--r--      268204 2019/04/02 13:02:05 wbxtrace/gpc/wbxtra_gpc_04022019_130150.wbt

Number of files: 17            
Number of files transferred: 0
Total file size: 30965184 bytes
Total transferred file size: 0 bytes
Literal data: 0 bytes
Matched data: 0 bytes
File list size: 548
File list generation time: 0.102 seconds
File list transfer time: 0.000 seconds
Total bytes sent: 564
Total bytes received: 20

sent 564 bytes  received 20 bytes  1168.00 bytes/sec
total size is 30965184  speedup is 53022.58
$ 

 

2. Using Find command.

$ find /tmp/  -print | wc -l
      17

 


III. Get count of only files(not directories) using find command.

$ find /tmp/ -type f -print
/tmp//.vbox-saket1447583-ipc/lock
/tmp//opensc-tokend.log

 


IV. Interesting way to calculate number of files using Loop

[root@ngelinux ~]# i=0; for j in `ls /tmp`; do ((i=$i+1)); done; echo $i
48
[root@ngelinux ~]# ls -l /tmp | wc -l
48
[root@ngelinux ~]# 

 

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments