cmd.exe批处理以裁剪dirname

时间:2015-08-26 11:44:27

标签: batch-file cmd rename

我的目录结构如下:

nnnnnn~substring

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

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

如何修剪目录名的所有数字和〜字符,以便只使用名称的最后部分重命名? 〜分隔符之前的数字有不同的长度,后面的子字符串也是如此。

1 个答案:

答案 0 :(得分: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
    )

重命名操作仅响应控制台。如果输出正确,请删除前缀echo命令

ren