You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何批量重命名\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.


方法1:Windows PowerShell

This is super straightforward if you're on Windows. Here's what to do:

  1. Open PowerShell and navigate to your Images folder using cd path\to\your\Images
  2. Run this command (add -WhatIf at 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 *.png grabs all PNG files in the folder
  • -split '_' breaks each filename into parts using underscores as separators
  • Select-Object -Last 1 picks the last part (which is your target number + extension)

方法2:macOS/Linux 终端

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
  • $1 uses 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

方法3:Python 脚本(跨平台)

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

火山引擎 最新活动