Home > other >  How to append a symbol before last 6 digit of a file name in batch script?
How to append a symbol before last 6 digit of a file name in batch script?

Time:09-17

I am creating a Batch script for following tasks:

  • Task 1: Find a specific name (.txt.) and replace with specific name(.txt_) in all the file name in a folder.

  • Task 2: Append a symbol(_) before last 6 digit of a file name in batch script.

    As IF: Test.txt.20210808654321

    To be: Test.txt_20210808_654321

I have created a script for Task 1 and it is working.

Script:

@echo off
setlocal enabledelayedexpansion

set "replace=.txt_"
set "find=.txt."

for %%i in ("C:\Script test\*.*") do (
   set name=%%~ni
   set ext=%%~xi
   ren "%%i" "!name:%find%=%replace%!!ext!"
)
pause

But I am struck in Task 2 (= Append a symbol(_) before last 6 digit of a file name).

Any help to finish it?

CodePudding user response:

Here's one way of doing it, without the need to use 'find' and 'replace' strings:

@For /F Delims^= %%G In ('Set "PATHEXT=" ^& %SystemRoot%\System32\where.exe
 ".":"*.txt.??????????????" 2^>NUL') Do @(Set "}=%%~xG"
    SetLocal EnableDelayedExpansion & For /F Delims^=. %%H In ("!}:~,9!_!}:~9!"
) Do @EndLocal & Ren "%%G" "%%~nG_%%~H")
  • Related