简体   繁体   中英

Batch script to read numerical part of file and rename with next higher integer

I have a file, such as -

foofile_1.ext

A script should read the numerical part of the file, and then rename the file with the next integer, ie, after execution, the file name should be

foofile_2.ext

I can do it with a C++ / c application or even in bash but not sure how to write a batch script to perform this rename. The filename before the _ isn't going to change, and _ will aaways appear in the same position within the filename.

I can strip the filename to _ , but recognizing the numerical is an implementation I am not familiar with. Once I recognize the numerical, I can increment it and rename the file.

Something to consider is that renaming foofile_1.ext to foofile_2.ext will fail should foofile_2.ext already exist. One way to get around it is to rename in descending numerical order, I posted an answer like that before on SO.

I am however not going to post the same answer here, nor link that answer. I will however show one other method:

@echo off
setlocal enabledelayedexpansion

for /f "tokens=1,*delims=_" %%i in ('dir /b /a-d "*_*.ext"') do (
     echo %%~nj | findstr /R /V /C:"[A-Z]">nul && (
     set /a numeric=%%~nj+1
     ren "%%~i_%%~j" "%%~i_-hld-!numeric!%%~xj"
   )
)
for /f "delims=" %%f in ('dir /b /a-d "*_-hld-*.ext"') do (
    set "name=%%~f"
    ren "%%~f" !name:-hld-=!
)

Considering that your input is as you said and does not contain earlier _ 's anywhere. This will just take each file with the *_*.ext format. We split by the _ into two tokened metavaiables ( %%i and %%j ) We take the numeric value and increment by one, then rejoin %%i which is pre _ . This however is where the problem comes when the file you are trying to rename to exists, so for that, first we test if %%~nj does not have Alphabetical characters only, using findstr (not doing special characters in this free code) Secondly we give a temporary addition to the name to prevent name clashing.

Once we are done, we simply do a rename on all the files containing the _-hld- temp inclusion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM