Skip to content

Instantly share code, notes, and snippets.

@dale-c-anderson
Last active September 24, 2020 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dale-c-anderson/e77979c8ddb45811a2bd74a6e6258c3f to your computer and use it in GitHub Desktop.
Save dale-c-anderson/e77979c8ddb45811a2bd74a6e6258c3f to your computer and use it in GitHub Desktop.
Flatten a directory structure by one level, preserving the full path of file names
#!/bin/bash
set -eu -o pipefail
# Turn:
# foo/
# ├── bar/
# │ ├── one.txt
# │ ├── two.txt
# ├── baz/
# ├── three.txt
# Into:
# foo-bar/
# ├── one.txt
# ├── two.txt
# foo-baz/
# foo-baz-three.txt
DIR=$1
if [ ! -d "$DIR" ]; then
>&2 echo "ERR: Not a directory: $DIR"
exit 1
fi
find "${DIR}" -maxdepth 1 -mindepth 1 -type d -exec sh -c 'new=$(echo "{}" | tr "/" "-" | tr " " "_"); mv -iv -- "{}" "$new"' \;
find "${DIR}" -maxdepth 1 -mindepth 1 -type f -exec sh -c 'new=$(echo "{}" | tr "/" "-" | tr " " "_"); mv -iv -- "{}" "$new"' \;
rmdir -v "${DIR}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment