Created
December 28, 2024 15:14
-
-
Save dbrack/cf50c6a3bf4b15965d17446454e79785 to your computer and use it in GitHub Desktop.
Recessively flatten a folder structure to have all files in one folder. Renames files to a random name to prevent naming conflicts in the target directory.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Check if source and destination directories are provided | |
| if [ "$#" -ne 2 ]; then | |
| echo "Usage: $0 source_directory destination_directory" | |
| exit 1 | |
| fi | |
| SOURCE_DIR="$1" | |
| DEST_DIR="$2" | |
| # Verify source directory exists | |
| if [ ! -d "$SOURCE_DIR" ]; then | |
| echo "Error: Source directory does not exist" | |
| exit 1 | |
| fi | |
| # Create destination directory if it doesn't exist | |
| mkdir -p "$DEST_DIR" | |
| # Initialize counter for progress tracking | |
| total_files=$(find "$SOURCE_DIR" -type f | wc -l) | |
| current=0 | |
| # Find all files recursively (including all nested subdirectories) and process them | |
| find "$SOURCE_DIR" -type f -print0 | while IFS= read -r -d $'\0' file; do | |
| ((current++)) | |
| # Get file extension (if any) | |
| filename=$(basename "$file") | |
| extension="${filename##*.}" | |
| # If the filename has no extension, don't add a dot | |
| if [ "$extension" = "$filename" ]; then | |
| random_name="$(openssl rand -hex 8)" | |
| else | |
| random_name="$(openssl rand -hex 8).${extension}" | |
| fi | |
| # Make sure the random name is unique in destination | |
| while [ -e "$DEST_DIR/$random_name" ]; do | |
| if [ "$extension" = "$filename" ]; then | |
| random_name="$(openssl rand -hex 8)" | |
| else | |
| random_name="$(openssl rand -hex 8).${extension}" | |
| fi | |
| done | |
| # Copy the file with the new name | |
| cp "$file" "$DEST_DIR/$random_name" | |
| # Show progress | |
| echo "Processed $current/$total_files: $file -> $random_name" | |
| done | |
| echo "Complete! All files have been copied to $DEST_DIR" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment