Find all file extensions used under some directory (recursively)


/ Published in: Bash
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # Not sure, what this is good for - however this is asked sometimes.
  2.  
  3. # I specifically exclude "dotfiles" and only consider files of the form "foo.bar" (i.e. we
  4. # don't consider filenames without an "inner dot" at all)
  5. find . -type f -name '[^.]*.*' \
  6. -exec bash -c 'printf "%s\n" ${@##*.}' _ {} + | sort -u
  7. # (or ... | sort | uniq, in case the sort lacks -u, which is a GNUism)
  8.  
  9. # Of course it's trivial to do it non-recursively:
  10. for f in *.*; do printf "%s\n" "${f##*.}"; done | sort -u
  11.  
  12. # or recursively again, with a bash4 associative array, including
  13. # a count for each extension (no sorting here):
  14. unset a; declare -A a
  15. while IFS= read -r ext; do
  16. ((a[$ext]++))
  17. done < <(find . -type f -name '[^.]*.*' \
  18. -exec bash -c 'printf "%s\n" ${@##*.}' _ {} +)
  19. for ext in "${!a[@]}"; do
  20. printf "'%s' (%s)\n" "$ext" "${a[$ext]}"
  21. done
  22.  
  23. # NOTE: all methods above fail, if an extension contains embedded newlines.

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.