#!/bin/sh # can improve by passing $@ to functions, but seems need bashism, or abandon functions # maybe use $1 for getext and use getopts, maybe seperate getext as another script, maybe add option for using ln instead of mv # references: # https://stackoverflow.com/questions/1842254/how-can-i-find-all-of-the-distinct-file-extensions-in-a-folder-hierarchy outdir () { find . -type f -execdir mv -t "$PWD" '{}' \+ find . -mindepth 1 -maxdepth 1 -type d -execdir rm -r '{}' \+ } # may further optimize by output file extension names to a variable and use it for both mkdir and mv, current is fast enough for me indir () { find . -maxdepth 1 -type f | awk -F. '!a[$NF]++{print $NF}' | xargs mkdir # don't know why -print0/-0 for find and xargs doesn't work here find . -mindepth 1 -maxdepth 1 -type d -execdir basename '{}' \; | xargs -I _ find . -maxdepth 1 -type f -name '*._' -execdir mv -t '_' '{}' \+ } case "$1" in '-o') outdir;; '-i') indir;; *) outdir; indir;; esac