mga revised this gist 1 year ago. Go to revision
1 file changed, 28 insertions
unwrap.sh(file created)
| @@ -0,0 +1,28 @@ | |||
| 1 | + | #!/bin/bash | |
| 2 | + | # This Bash script flattens a directory structure. | |
| 3 | + | # It finds files in subdirectories, moves them to a base directory, and renames them to avoid conflicts. Finally, it removes any directories that become empty after the move. | |
| 4 | + | ||
| 5 | + | # Function to move and rename files if necessary | |
| 6 | + | move_and_rename() { | |
| 7 | + | local src_file="$1" | |
| 8 | + | local base_dir="$2" | |
| 9 | + | local filename=$(basename "$src_file") | |
| 10 | + | local dest_file="$base_dir/$filename" | |
| 11 | + | local counter=1 | |
| 12 | + | ||
| 13 | + | # Rename the file if a file with the same name already exists | |
| 14 | + | while [ -e "$dest_file" ]; do | |
| 15 | + | dest_file="$base_dir/${filename%.*}_$counter.${filename##*.}" | |
| 16 | + | counter=$((counter + 1)) | |
| 17 | + | done | |
| 18 | + | ||
| 19 | + | mv "$src_file" "$dest_file" | |
| 20 | + | } | |
| 21 | + | ||
| 22 | + | export -f move_and_rename | |
| 23 | + | ||
| 24 | + | # Find and move files | |
| 25 | + | find . -mindepth 2 -type f -exec bash -c 'move_and_rename "$0" "$PWD"' {} \; | |
| 26 | + | ||
| 27 | + | # Remove empty directories | |
| 28 | + | find . -type d -empty -delete | |
Newer
Older