How to count files by extension in linux
ls command is heart for linux user. ls command is very very basic and most frequently used command in Linux. I know every body first use ls command when their logged into system/server. Everybody’s know ls command is used to list the content’s of directory but most of them don’t know all the important option of ls command.
We are running online portal with images and our IT team person ask me to send images count with extension. That time i used these commands to done the job.
For testing purpose, i have created ramya folder under home directory and put 1 jpg file & 3 png file. And i created another folder called magesh under ramya directory and put 1 png file to check recursively the command working or not. See below details.
[email protected] [/home/ramya]# ls -lh total 120K drwx------. 3 ramya ramya 4.0K Jul 31 15:24 ./ drwx--x--x. 27 root root 4.0K Jul 30 01:17 ../ -rw-r--r--. 1 root root 143 Jul 31 15:01 bg-input.png -rw-r--r--. 1 root root 57K Jul 31 15:01 bg_login_top.jpg -rw-r--r--. 1 root root 2.8K Jul 31 15:01 index.png -rw-r--r--. 1 root root 33K Jul 31 15:01 sprite.png [email protected] [/home/ramya]# mkdir magesh [email protected] [/home/ramya]# cd magesh [email protected] [/home/ramya/magesh]# ls -lh total 12K drwxr-xr-x. 2 root root 4.0K Jul 31 15:02 ./ drwx------. 3 ramya ramya 4.0K Jul 31 15:24 ../ -rw-r--r--. 1 root root 143 Jul 31 15:01 bg-input-focus.png
1) How to count files by specific extension ?
The below command is counting only specific extension files within a directory and not recursively, like if i mention .png its count only .png file on current directory. You need to mention your file extension which you want to count. Here i have checked two type of extension and pasted the details.
[email protected] [/home/ramya]# ls *.png -l | wc -l 3 or [email protected] [/home/ramya]# ls *.jpg -l | wc -l 1
2) How to count all files extension in linux ?
The below command is counting all file extensions separately and recursively. Both are different but giving same results. This will shows 4 png because its counted recursively (counted under magesh directory png file). See the below output
[email protected] [/home/ramya]# find . -type f | sed -n 's/..*\.//p' | sort | uniq -c 1 jpg 4 png