Skip to content

Instantly share code, notes, and snippets.

@dbrack
Created December 28, 2024 15:14
Show Gist options
  • Select an option

  • Save dbrack/cf50c6a3bf4b15965d17446454e79785 to your computer and use it in GitHub Desktop.

Select an option

Save dbrack/cf50c6a3bf4b15965d17446454e79785 to your computer and use it in GitHub Desktop.

Revisions

  1. dbrack created this gist Dec 28, 2024.
    56 changes: 56 additions & 0 deletions flatten-folder.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    #!/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"