You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows批处理文件重命名:如何保留文件名最后8个字符

Batch File Rename: Preserve Last 8 Characters While Formatting Date

Got it, let's work through this batch renaming problem. You already have the prefix and date handling sorted, so the main trick here is using batch's built-in string manipulation to grab the last 8 characters of your filename. Here's a complete solution tailored to your needs:

Step-by-Step Script

@echo off
setlocal enabledelayedexpansion

:: Loop through all matching Rapp_*.tif files
for %%f in (Rapp_*.tif) do (
    :: Extract the core filename (without extension)
    set "original_filename=%%~nf"
    :: Grab the LAST 8 characters of the full filename (including extension) - this is your "_001.tif" part
    set "suffix=%%~nxf:~-8"
    
    :: Extract the raw date string from the original filename (adjust the indices if your date position differs)
    :: Original example: "Rapp_20220628150328_001" → raw date is "20220628" (starts at index 5, 8 characters long)
    set "raw_date=!original_filename:~5,8!"
    
    :: Split raw date into year, month, day
    set "year=!raw_date:~0,4!"
    set "month=!raw_date:~4,2!"
    set "day=!raw_date:~6,2!"
    
    :: Format the date into YYYY_MM_GG
    set "formatted_date=!year!_!month!_!day!"
    
    :: Build the new filename
    set "new_filename=Rapp_!formatted_date!!suffix!"
    
    :: Execute the rename (add echo before ren to test first if you want)
    ren "%%f" "!new_filename!"
)

echo Renaming completed successfully!
endlocal

Key Details Explained

  • setlocal enabledelayedexpansion: This is critical for variables inside the for loop to update correctly. Without it, batch would evaluate all variables once at the start of the loop instead of per-file.
  • %%~nxf:~-8: The :~-8 syntax tells batch to take the last 8 characters of the full filename (name + extension). Exactly what you need to preserve _001.tif.
  • Date Extraction: !original_filename:~5,8! pulls the 8-character date string starting at index 5 (since "Rapp_" is 5 characters long). Adjust these numbers if your original filename structure varies.
  • Safety Tip: Add echo before ren (like echo ren "%%f" "!new_filename!") to preview changes without actually renaming files first.

Example Output

For your test file Rapp_20220628150328_001.tif, the script will generate:
Rapp_2022_06_28_001.tif

内容的提问来源于stack exchange,提问作者Daniele

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 01:27:31