如何将多文件夹中的同名文件按文件名归类并解决重名冲突
Got it, let's sort this out efficiently. You've got 400 folders each nested 3 levels deep with 22 identical filenames spread across them, and you need to group every file by its name while avoiding duplicates. Here are two robust, automated solutions to get this done quickly:
Shell Script Solution (Linux/macOS)
This script works natively on Linux and macOS, leveraging find and basic shell commands to handle the heavy lifting. It'll create your 22 target folders, hunt down all matching files, and rename duplicates using the last 6 characters of their parent path to keep things unique.
# Replace this with the path to your 400 main folders ROOT_DIR="./your_root_folder" # Replace these sample filenames with your actual 22 unique file names for filename in "report.pdf" "data.csv" "log.txt" "image.jpg"; do # Create a destination folder for each file type (adjust the name format if needed) DEST_FOLDER="./${filename}_collection" mkdir -p "$DEST_FOLDER" # Find every instance of the current file in the root directory find "$ROOT_DIR" -name "$filename" -type f | while read -r file_path; do # Grab the last 6 characters of the file's parent directory (strip slashes to avoid issues) path_suffix=$(dirname "$file_path" | tail -c 7 | tr -d '/') # Fallback to the parent folder name if the path is shorter than 6 characters if [ -z "$path_suffix" ]; then path_suffix=$(basename "$(dirname "$file_path")") fi # Build the new unique filename new_filename="${filename%.*}_${path_suffix}.${filename##*.}" # Copy the file to its new home cp "$file_path" "$DEST_FOLDER/$new_filename" echo "Copied: $file_path → $DEST_FOLDER/$new_filename" done done
Quick Setup Tips for Shell:
- Swap
./your_root_folderwith the actual path where your 400 folders live. - Update the
for filenamelist with all 22 of your unique file names. - If you want the destination folder to match the filename exactly (e.g.,
report.pdfinstead ofreport.pdf_collection), changeDEST_FOLDER="./${filename}_collection"toDEST_FOLDER="./${filename}".
Python Script Solution (Cross-Platform)
If you're on Windows, or prefer a cross-platform tool that works everywhere, this Python script will handle the same task while preserving file metadata like creation dates.
import os import shutil # Configuration - update these values to match your setup ROOT_DIR = "./your_root_folder" # Path to your 400 main folders UNIQUE_FILENAMES = ["report.pdf", "data.csv", "log.txt", "image.jpg"] # Your 22 unique file names for filename in UNIQUE_FILENAMES: # Create the destination folder (no error if it already exists) dest_folder = os.path.join(os.getcwd(), f"{filename}_collection") os.makedirs(dest_folder, exist_ok=True) # Recursively scan all folders for the current file for root, _, files in os.walk(ROOT_DIR): if filename in files: file_path = os.path.join(root, filename) # Get the last 6 characters of the parent directory (strip directory separators) parent_dir = os.path.dirname(file_path) path_suffix = parent_dir[-6:].replace(os.sep, "") # Fallback to parent folder name if the path is too short if not path_suffix: path_suffix = os.path.basename(parent_dir) # Build the unique filename name, ext = os.path.splitext(filename) new_filename = f"{name}_{path_suffix}{ext}" dest_path = os.path.join(dest_folder, new_filename) # Copy the file (preserves metadata like creation/modification times) shutil.copy2(file_path, dest_path) print(f"Copied: {file_path} → {dest_path}")
Quick Setup Tips for Python:
- Install Python if you haven't already (it's free and easy to set up).
- Update
ROOT_DIRandUNIQUE_FILENAMESto match your actual files and folder structure. - Like the shell script, you can adjust the
dest_folderline to use the filename directly if preferred.
Pro Tips
- Test first: Run the script on a small subset of your folders first to confirm the renaming and copying works as expected.
- Adjust the suffix: If you want to use a different part of the path (e.g., the last 6 characters of the full path including the filename), tweak the
path_suffixlogic in either script. - Move instead of copy: If you don't need to keep the original files, replace
cpwithmvin the shell script, orshutil.copy2withshutil.movein the Python script.
内容的提问来源于stack exchange,提问作者CandleWax

