Created
June 5, 2025 08:27
-
-
Save CuddlyBunion341/10584b6616c0c48c198d7bc508307c93 to your computer and use it in GitHub Desktop.
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 a directory to flatten is provided | |
if [ $# -ne 2 ]; then | |
echo "Usage: $0 <directory_to_flatten> <target_directory>" | |
exit 1 | |
fi | |
SOURCE_DIR="$1" | |
TARGET_DIR="$2" | |
# Check if the source directory exists | |
if [ ! -d "$SOURCE_DIR" ]; then | |
echo "Error: Directory '$SOURCE_DIR' does not exist." | |
exit 1 | |
fi | |
# Create the target directory if it does not exist | |
mkdir -p "$TARGET_DIR" | |
# Find all files in the source directory and subdirectories | |
find "$SOURCE_DIR" -type f | while read -r file; do | |
# Get the filename without the path | |
filename=$(basename "$file") | |
# Move the file to the target directory | |
# If a file with the same name exists, append a number to the filename | |
target_file="$TARGET_DIR/$filename" | |
if [ -e "$target_file" ]; then | |
counter=1 | |
while [ -e "$target_file" ]; do | |
target_file="$TARGET_DIR/${filename%.*}_$counter.${filename##*.}" | |
counter=$((counter + 1)) | |
done | |
fi | |
mv "$file" "$target_file" | |
echo "Moved: $file -> $target_file" | |
done | |
echo "Flattening complete." | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Before
After