重命名文件 "The syntax of the command is incorrect" .bat

Rename files "The syntax of the command is incorrect" .bat

我正在尝试从多个目录中的多个文件名中删除一个字符串。这是与正在创建的一些文件一样的文件,以便我可以检查实际设置的值。

当我到达最底部的 rename 时,出现错误:

The syntax of the command is incorrect.

我在创建的 _intf_fnlf 文本文件中没有发现任何问题。在重命名中使用变量作为文件路径有什么技巧吗?

@ECHO off

echo Delete dir.txt?
PAUSE

del dir.txt
del item.txt
del file.txt

::paths for all directories in root (where filerename.bat is run)
 ::get root dir path
 SET "_c=%CD%"
 SET /A "counter=0"
 ::get dir list and concats root dir path before
 FOR /F "tokens=*" %%A in ('DIR /on /b /a:d /p %svnLOCAL%') DO ( 
    SET "_dirp=%_c%\%%A"
    CALL :sub1
    SET /A "_counter+=1"
 )

::finds each file in dir
:sub1
 ::make file to check dir path
 ECHO "%_dirp%" > dir.txt
 FOR /F "tokens=*" %%B in ('DIR /b %_dirp%') DO (
  ECHO "%%B" > item.txt
  SET "_item=%%B"
  SET "_filep=%_dirp%\"
  CALL :sub2 %%~nB
PAUSE
 )
 ECHO "%_counter%"
EXIT /b 0

::builds file paths
:sub2
 set "str=%*"
 set "str=%str:[1]=%"
 SET "_intf=%_filep%%_item%"
 SET "_fnlf=%_filep%%str%"
 CALL :sub3
EXIT /b 0

::Renames each file
:sub3
 ECHO "%_intf%" > _intf.txt
 ECHO "%_fnlf%" > _fnlf.txt
 ren "%_intf%" "%_fnlf%.jpg"
EXIT /b 0

你的错误是因为你没有正确使用 REName 命令。

这可以通过在命令提示符下输入 Ren /? 来记录,语法显示为:

REN [drive:][path]filename1 filename2

然而你似乎在使用:

REN [drive:][path]filename1 [drive:][path]filename2

...这将产生错误:

The syntax of the command is incorrect.

作为脚本的简单修复,您需要更改以下行:

set "str=%str:[1]=%"

至:

set "_fnlf=%str:[1]=%"

然后删除行:

SET "_fnlf=%_filep%%str%"

如果您想整理代码,您可以将其更改为:

@Echo Off
Set "i=0"
For /F "Delims=" %%A In ('Dir /B/AD "%svnLOCAL%" 2^>Nul') Do (
    Set /A i+=1
    For /F "Delims=" %%B In ('Dir /B/A-D "%~dp0%%A\*[1]*" 2^>Nul') Do (
        Set "$=%%~nB"
        Call Ren "%~dp0%%A\%%B" "%%$:[1]=%%.jpg"
    )
)
Echo "%i%"
Pause

或使用延迟扩展:

@Echo Off
Set "i=0"
For /F "Delims=" %%A In ('Dir /B/AD "%svnLOCAL%" 2^>Nul') Do (
    Set /A i+=1
    For /F "Delims=" %%B In ('Dir /B/A-D "%~dp0%%A\*[1]*" 2^>Nul') Do (
        Set "$=%%~nB"
        SetLocal EnableDelayedExpansion
        Ren "%~dp0%%A\%%B" "!$:[1]=!.jpg"
        EndLocal
    )
)
Echo "%i%"
Pause

在上面的两个示例中,我将您的评论 where filerename.bat is run 表示为该脚本 filerename.bat 所在的目录。如果您指的是当前工作目录,不一定相同,您应该将上面的 %~dp0 实例替换为 %__CD__%

此外,由于您提供的信息不明确,我假设 %svnLOCAL% 已经定义。