JavaScript文件夹批量重命名:多字符串替换对实现问题求助
Hey there! Let's tackle this filename bulk replacement problem efficiently—no need to write separate loops for each replacement pair. The core idea is to store all your 12 replacement rules in a single mapping structure (like a dictionary or hash table), then apply every rule to each filename in one pass.
Python Cross-Platform Solution
This works on Windows, macOS, and Linux, and keeps your code clean and easy to update:
import os # Step 1: Define all your replacement pairs in a single dictionary # Add your remaining 10 pairs directly here replace_rules = { "BUL": "Bg-bg", "ENG": "En-us", "FRA": "Fr-fr", "DEU": "De-de", "ESP": "Es-es" } # Step 2: Set your target folder path target_folder = "/path/to/your/target/directory" # Step 3: Process each file in the folder for filename in os.listdir(target_folder): file_path = os.path.join(target_folder, filename) # Skip subfolders, only process files if not os.path.isfile(file_path): continue # Apply all replacement rules to the filename new_filename = filename for old_str, new_str in replace_rules.items(): new_filename = new_filename.replace(old_str, new_str) # Only rename if the filename actually changed if new_filename != filename: new_file_path = os.path.join(target_folder, new_filename) os.rename(file_path, new_file_path) print(f"Renamed: {filename} → {new_filename}")
Why this works:
- All your replacement logic lives in one place (
replace_rules), so updating/adding pairs is just a matter of editing the dictionary. - We only loop through the files once, and apply every rule to each filename in a nested loop—no redundant code.
- The check for
new_filename != filenameavoids unnecessary rename operations.
PowerShell Windows-Friendly Solution
If you prefer using PowerShell (great for Windows environments), here's a similar approach:
# Step 1: Define replacement pairs in an ordered hash table # Use [ordered] if you need to enforce replacement order (e.g., replace longer strings first) $replaceRules = [ordered]@{ "BUL" = "Bg-bg" "ENG" = "En-us" # Add your remaining replacement pairs here } # Step 2: Set your target folder path $targetFolder = "C:\Path\To\Your\Folder" # Step 3: Process each file Get-ChildItem -Path $targetFolder -File | ForEach-Object { $newName = $_.Name # Apply every replacement rule foreach ($oldStr in $replaceRules.Keys) { # Use [regex]::Escape to handle special characters in your search strings $newName = $newName -replace [regex]::Escape($oldStr), $replaceRules[$oldStr] } # Rename only if changes were made if ($newName -ne $_.Name) { Rename-Item -Path $_.FullName -NewName $newName Write-Host "Renamed: $($_.Name) → $newName" } }
Key Notes:
- The
[ordered]attribute ensures replacements happen in the order you define (critical if, for example, one search string is a substring of another—e.g., replacing "ABC" before "AB"). [regex]::Escapeprevents issues if your search strings contain special regex characters (like$or.).
Edge Case Tips
- Recursive Subfolder Handling: To process files in subfolders too:
- In Python: Use
os.walk(target_folder)instead ofos.listdirto traverse all subdirectories. - In PowerShell: Add the
-Recurseflag toGet-ChildItem.
- In Python: Use
- Case Sensitivity: By default, Python's
str.replaceis case-sensitive. If you need case-insensitive replacement, use a regex with there.IGNORECASEflag instead. - Duplicate Filenames: Add a check to avoid overwriting existing files (e.g., append a number if
new_file_pathalready exists).
内容的提问来源于stack exchange,提问作者Ilia Shifrin
相关产品推荐
相关产品推荐

