如何批量重命名\Images文件夹文件,仅保留最后下划线后数字及后缀?
Hey there! Let me walk you through a few reliable ways to batch rename those image files exactly how you want—keeping only the number after the last underscore plus the file extension.
This is super straightforward if you're on Windows. Here's what to do:
- Open PowerShell and navigate to your
Imagesfolder usingcd path\to\your\Images - Run this command (add
-WhatIfat the end first to preview changes without actually renaming):
Get-ChildItem -Filter *.png | Rename-Item -NewName { $_.Name -split '_' | Select-Object -Last 1 }
解释:
Get-ChildItem -Filter *.pnggrabs all PNG files in the folder-split '_'breaks each filename into parts using underscores as separatorsSelect-Object -Last 1picks the last part (which is your target number + extension)
If you're on a Unix-like system, you have a couple options:
选项A:使用rename命令(大部分系统预装)
Run this in your Images directory (test first with the -n flag to preview):
rename -n 's/.*_(\d+\.png)/$1/' *.png
Once you're happy with the preview, remove the -n to apply the changes:
rename 's/.*_(\d+\.png)/$1/' *.png
解释:
- The regex
.*_matches everything up to the last underscore (\d+\.png)captures the number sequence followed by.png$1uses that captured group as the new filename
选项B:使用mv + awk(更兼容,无rename也能用)
Run this loop (again, replace mv with echo mv first to preview):
for file in *.png; do new_name=$(echo "$file" | awk -F '_' '{print $NF}') mv "$file" "$new_name" done
解释:
awk -F '_' '{print $NF}'splits the filename by underscores and prints the last field
If you prefer a script that works everywhere, save this as rename_images.py in your Images folder:
import os folder_path = os.getcwd() # Uses current directory; you can replace with your path for filename in os.listdir(folder_path): if filename.endswith(".png"): # Split filename by underscores and take the last part new_name = filename.split("_")[-1] # Avoid overwriting existing files (optional but safe) if not os.path.exists(new_name): os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_name)) else: print(f"Skipping {filename} - {new_name} already exists")
Then run it with python rename_images.py from the terminal/PowerShell.
内容的提问来源于stack exchange,提问作者James Smith




