Ubuntu – Find the number of files for each extension in a directory

command lineextensionfind

I want to count the number of files for each extension in a directory as well as the files without extension.

I have tried a few options, but I haven't found a working solution yet:

  • find "$folder" -type f | sed 's/.*\.//' | sort | uniq -c is an option but doesn't work if there is no file extension. I need to know how many files do not have an extension.

  • I have also tried a find loop into an array and then sum the results, but at this time that code throws an undeclared variable error, but only outside of the loop:

    declare -a arr
    arr=()
    echo ${arr[@]}
    

    This throws an undeclared variable, as well as once the find loop completes.

Best Answer

find "$path" -type f | sed -e '/.*\/[^\/]*\.[^\/]*$/!s/.*/(none)/' -e 's/.*\.//' | LC_COLLATE=C sort | uniq -c

Explanation:

  • find "$path" -type f get a recursive listing of all the files on the "$path" folder.
  • sed -e '/.*\/[^\/]*\.[^\/]*$/!s/.*/(none)/' -e 's/.*\.//' regular expressions:
    • /.*\/[^\/]*\.[^\/]*$/!s/.*/(none)/ replace all the files without extension by (none).
    • s/.*\.// get the extension of the remaining files.
  • LC_COLLATE=C sort sort the result, keeping the symbols at the top.
  • uniq -c count the number of repeated entries.