Skip to content

Instantly share code, notes, and snippets.

@petrabarus
Last active August 30, 2023 04:02
Show Gist options
  • Save petrabarus/b3ec6c334660fbe329031bc547424161 to your computer and use it in GitHub Desktop.
Save petrabarus/b3ec6c334660fbe329031bc547424161 to your computer and use it in GitHub Desktop.
Find all files in a directory, flatten, and rename to UUID
#!/usr/bin/env bash
# This script will find all files in the current directory and rename them using UUID and flatten the directory structure.
# This script is useful when you have a directory structure like this:
# src/dir1/dir2/dir3/file1.txt
# src/dir1/dir2/dir4/file2.txt
# src/dir1/dir2/file3.txt
#
# And you want to flatten it to this:
# dest/6f4f6995-0d76-4b53-829a-dfa480b2591f.txt
# dest/a453bc30-4631-447d-8f60-d36bb8b372cc.txt
# dest/9ba5fbd9-6a59-4253-b948-dc9116dab727.txt
# Get the source directory from first argument
current_dir=$1
# Get the destination directory from second argument
destination_dir=$2
# Find all files in the current directory
find $current_dir -type f | while read file; do
# Get the filename without the path
filename=$(basename "$file")
# Get the extension of the file
extension="${filename##*.}"
# Get the filename without the extension
filename="${filename%.*}"
# Generate a UUID
uuid=$(uuidgen | tr "[:upper:]" "[:lower:]")
# Rename the file to UUID.extension
echo "$file" "$destination_dir/$uuid.$extension"
mv "$file" "$destination_dir/$uuid.$extension"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment