February 27, 2012

find all file extensions used under some directory


# Not sure, what this is good for - however this is asked sometimes.

# I specifically exclude "dotfiles" and only consider files of the form "foo.bar" (i.e. we
# don't consider filenames without an "inner dot" at all)
find . -type f -name '[^.]*.*' \
       -exec bash -c 'printf "%s\n" ${@##*.}' _ {} + | sort -u
# (or ... | sort | uniq, in case the sort lacks -u, which is a GNUism)

# Of course it's trivial to do it non-recursively:
for f in *.*; do printf "%s\n" "${f##*.}"; done | sort -u

# or recursively again, with a bash4 associative array, including
# a count for each extension (no sorting here):
unset a; declare -A a
while IFS= read -r ext; do
    ((a[$ext]++))
done < <(find . -type f -name '[^.]*.*' \
         -exec bash -c 'printf "%s\n" ${@##*.}' _ {} +)
for ext in "${!a[@]}"; do
    printf "'%s' (%s)\n" "$ext" "${a[$ext]}"
done

# NOTE: all methods above fail, if an extension contains embedded newlines.


@credit goes to http://snipplr.com/view.php?codeview&id=26672

No comments:

Post a Comment

How to type letters with accent

Very useful article https://www.freecodecamp.org/news/how-to-type-letters-with-accents-on-mac/