Count total number of files in particular directory with specific extension

I want to count the total number of files in particular directory that ends with ".mp4" extension.

I am getting following command:

ls -F |grep -v / | wc -l

It count all the files in particular directory, but I want the count of files that end with .mp4 extension.

Is there any Ubuntu command for that?


Solution 1:

Unfortunately this benign problem is difficult to solve in a way which supports all file names and is portable. This is safe (it handles hidden files, paths containing spaces, dashes and even newlines) and POSIX compatible:

find /path/to/directory -mindepth 1 -type f -name "*.mp4" -printf x | wc -c

If you don't want it to be recursive, simply add -maxdepth 1.

You shouldn't parse ls output.

Test:

$ cd -- "$(mktemp -d)"
$ touch -- -foo.mp4 .bar.mp4 .bat.mp4 'baz.mp4
> ban.mp4'
$ find . -mindepth 1 -type f -name "*.mp4" -exec printf x \; | wc -c
4

Compare with the accepted answer:

$ ls -lR ./*.mp4 | wc -l
3

Or other suggestions:

$ find . -name "*.mp4" | wc -l
5
$ ls -1 *.mp4 | wc -l
ls: invalid option -- '.'
Try 'ls --help' for more information.
0
$ find . -name "*.mp4" | wc -c # Answer fixed at a later time
51
$ find . -name "*.mp4" | wc -l
5
$ find . | grep -i ".mp4$" | wc -l
5
$ ls . | grep ".mp4$" | wc -l
3

Solution 2:

Here you can do this way

ls -lR /path/to/dir/*.jpg | wc -l

This gives you count

Solution 3:

This one finds, sorts, and lists all files by extension in order:

find . -type f | sed 's/.*\.//' | sort | uniq -c

Solution 4:

I think it's very simple as following commands.

$ find . -name "*.mp4" | wc -l
8

or

$ find . | grep -i ".mp4$" | wc -l
8

I think that above commands calculate count of files and directories names *.mp4

so I suggest you use -type f option as find parameter as following.

$ find . -name "*.mp4" -type f | wc -l
8

In addition, ls -lR can be used as find .