#!/bin/bash function help() { echo "Flatten the directory structure from the current folder downwards" echo "Files in subfolders will be renamed / -> _" echo "Empty folders are removed" echo " -f to force action " echo " -n to move files as is, i.e. not include path names in new name " echo " -H include hidden files/folders " echo " -p C Replace path separator / with character C " } function helpexit() { help exit } function finder() { if [[ "$FILTER" -eq 0 ]]; then find . -mindepth 2 -type f -path '*.*' -printf %P'\n' return $? fi if [[ "$FILTER" -eq 1 ]]; then find . -mindepth 2 -not -path '*/\.*' -type f -printf %P'\n' return $? fi } function preview() { echo "" for f in $( finder | head ); do [[ "$NO_PATH" = "1" ]] && { echo "$f => " . } || { echo "$f =>" "${f//\//$SEP}" } done echo "..." } function flat() { [[ "$FORCE" = "0" ]] && INTERACT="-i" for f in $( finder ); do [[ "$NO_PATH" = "1" ]] && { mv -v $INTERACT "$f" . } || { mv -v $INTERACT "$f" "${f//\//$SEP}" } done find . -depth -type d -empty -delete } SEP="_" FORCE=0 FILTER=1 while getopts fhHnp: opt do case "$opt" in f) FORCE=1 ;; h) helpexit ;; H) FILTER=0 ;; n) NO_PATH=1 ;; p) SEP=$OPTARG ;; esac done IFS=$'\n' [[ "$FORCE" = "0" ]] && { help preview echo "Are you sure? Break with ctrl-c" read i } flat