How to Get the Count of Files with each File Extension in Linux
One interesting command I learned lists all file extensions in a directory and counts them.
Let’s see how it works.
List All File Extensions
find . -type f | grep -i -E -o "\.\w*$" | sort -su
find . -type f searches for all files in the current and subdirectories.
| pipes the output from the previous command to the next command.
-i forces grep to perform case insensitive matching, so it will find .jpeg and .JPEG.
-E allows us to use extended regular expressions. In our case, it allows us to use {} the way we do here. Alternatively, we could use egrep and remove this flag.
-o forces grep to print only the matching portion of the regular expression, instead of the entire line like it defaults to.
\. matches a single literal period ..
\w* matches any number of word characters (from 0 to infinity).
$ ensures that the expression occurs at the end of the line.
sort -su performs a stable, unique sorting of the previous output.
.css
.gitkeep
.html
.jpg
.js
.md
.png
.sample
.sh
.svg
.toml
.txt
.xml
.yaml
List All File Extensions with Count
find . -type f | grep -i -E -o "\.\w*$" | sort | uniq -c
sort | uniq is the same as sort -u, but allows us to use the uniq command’s -c flag.
8 .css
2 .gitkeep
62 .html
2 .jpg
5 .js
37 .md
226 .png
12 .sample
1 .sh
4 .svg
1 .toml
1 .txt
10 .xml
1 .yaml