获取名称中包含字符串的文件数

时间:2018-05-23 07:44:17

标签: windows batch-file cmd

我在上下文菜单中创建了一个custom submenu,当我遇到问题时我会对其进行更新。

它的工作方式是我有模板文件。每当我单击子菜单上的项目(文件类型)时,该模板文件将被复制到当前文件夹并重命名。例如:

@echo off
copy C:\Windows\CustomNew\templates\html.html "%cd%"
rename html.html "New HTML Document.html"

此代码的问题在于,如果我创建两个HTML文件,则首先重命名一个,但第二个不重命名。那是因为当前文件夹中已经有一个名为"New HTML Document.html"的文件。所以它只是"html.html"。为了解决这个问题,我试过了:

@echo off

setlocal enabledelayedexpansion

copy C:\Windows\CustomNew\templates\html.html "%cd%"

set name="New HTML Document.html"

if exist %name% (
    set name="New HTML Document (2).html"
)

rename html.html !name!

这样可行,但如果我想创建两个以上的文件呢?我还有最初的问题。要解决这个问题,我需要在其名称中获取包含"New HTML Document"的文件数,向其中添加1,并相应地重命名新文件。我该怎么做?

1 个答案:

答案 0 :(得分:5)

实现计数器和循环:

@ECHO OFF
break>html.html
setlocal enabledelayedexpansion

set "name=New HTML Document.html"
set count=0

:loop
if not exist "%name%" goto :continue
set /a count+=1
set "name=New HTML Document (%count%).html"
goto :loop

:continue
rename html.html "%name%"
dir new*