Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

How do I increment a folder name using Windows batch?

I've got a batch script that creates a folder named New_Folder and a few subdirectories and files within. Currently, if I need to create multiple New_Folders I have to rename each New_Folder created by the batch before I can run it again and create a new one. What I'd like to do is have the batch check and see if New_Folder already exists, and if so, to increment New_Folder by a number. So I'd have New_Folder, New_Folder1, New_Folder2, and so on.

How would I go about doing this? The solutions I've seen for incrementing things in batch scripts don't seem to apply to my situation, and I don't know anything about batch scripting beyond what I've copy/pasted for my own code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a solution that will always work, even if there are gaps in the numbers. The folder number will always be 1 greater than the current max number.

@echo off
setlocal enableDelayedExpansion
set "baseName=New_Folder"
set "n=0"
for /f "delims=" %%F in (
  '2^>nul dir /b /ad "%baseName%*."^|findstr /xri "%baseName%[0-9]*"'
) do (
  set "name=%%F"
  set "name=!name:*%baseName%=!"
  if !name! gtr !n! set "n=!name!"
)
set /a n+=1
md "%baseName%%n%"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[2] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

56.8k users

...