2015-08-26 25 views
0

我有读起来就像一个目录结构:CMD.EXE批量裁剪目录名称

nnnnnn~substring 

n是数字和substring是字母。 我正在尝试编写一个批处理文件,用于测试目录中是否存在特定的文件,如果存在,它应该将该目录重命名为substring。 批处理文件应该是这样的:

for /f "tokens=\*" %%a in ('dir /b') do if exist filename (rename nnnnnn~substring substring) 

如何修剪所有的数字和目录名的〜字符,所以我可以只使用名字的最后一部分改名? 〜分隔符之前的数字具有不同的长度,其后的子串也是如此。

+1

编辑问题并指定是什么问题。 – wOxxOm

回答

2
@echo off 
    setlocal enableextensions disabledelayedexpansion 

    rem Change to the target folder 
    pushd "x:\somewhere" && (

     rem For each folder inside it matching the indicated pattern 
     rem  Uses a dir command to search only folders and a 
     rem  findstr filter to ensure only matching folders 
     for /f "delims=" %%a in (' 
      dir /ad /b *~* ^| findstr /r /c:"^[0-9][0-9]*~..*$" 
     ') do (

      rem Check if the folder contains the file 
      if exist "%%~fa\flagFile.txt" (

       rem Split the folder name using the ~ as delimiter 
       for /f "tokens=1,* delims=~" %%b in ("%%~na") do (

        rem Check that the new folder name does not exist 
        if not exist "%%~c%%~xa" (
         rem Execute the rename operation 
         echo ren "%%~fa" "%%~c%%~xa" 
        ) 
       ) 
      ) 
     ) 
     rem Restore previous active directory 
     popd 
    ) 

重命名操作只回应到控制台。如果输出是正确的,删除​​前缀ren命令

0

这可能工作echo - 在你的文件夹结构的副本进行测试:
它假定substring在你的问题中不包含任何~字符。

@echo off 
:loop 
for /d /r "d:\base\folder" %%a in (*~*) do (
    if exist "%%a\filename" for /f "tokens=1,* delims=~" %%b in ("%%~nxa") do (
    ren "%%a" "%%c" 
    goto :loop 
) 
) 
pause 

这是仅为当前目录中的文件夹而设计的。

@echo off 
for /d %%a in (*~*) do (
    if exist "%%a\filename" for /f "tokens=1,* delims=~" %%b in ("%%~nxa") do ren "%%a" "%%c" 
) 
pause 
+0

如果您的文件夹结构不包含嵌套子目录,则可以简化此操作。 – foxidrive

+0

它做的工作,但然后循环重复错误“文件已存在或文件未找到”,我不得不停止它与Ctrl-C。顺便说一句:没有嵌套的目录。 – Ignasi

+0

@Ignasi你用什么名字来批处理文件?所有'substring'部分都是唯一的吗? – foxidrive