Batch file 如何提取文件名的中间部分以创建新的文件名?

Batch file 如何提取文件名的中间部分以创建新的文件名?,batch-file,Batch File,我需要从源程序创建的默认文件名创建一个新文件名 我需要在文件名的末尾添加修订,但也需要在默认文件名的开头添加前缀 默认文件名如下所示:drw1234567_1.dxf 我需要将其更改为1234567\u drw1234567\u 1Rev0A.dxf 我已经能够在脚本中创建“REVISION”和“PAGE”参数,但无法获取“PART_编号”。任何帮助都将不胜感激 rem extract_revision_parameter.BAT REM // Parse drawing_parameter f

我需要从源程序创建的默认文件名创建一个新文件名

我需要在文件名的末尾添加修订,但也需要在默认文件名的开头添加前缀

默认文件名如下所示:
drw1234567_1.dxf

我需要将其更改为
1234567\u drw1234567\u 1Rev0A.dxf

我已经能够在脚本中创建“REVISION”和“PAGE”参数,但无法获取“PART_编号”。任何帮助都将不胜感激

rem extract_revision_parameter.BAT
REM // Parse drawing_parameter file for revision number
FOR /F "usebackq tokens=2" %%a IN (`find "REVISION" C:\dxf\in\draw_parameter*.txt`) DO SET REVISION=Rev%%a
FOR %%a IN ( C:\dxf\in\*.DXF) DO (SET %%a)
pause
REM // Retrieve page number with underscore from file name by 
REM //skipping the first 7 digits that represent the part number
FOR %%i IN (C:\dxf\in\*.dxf) DO (
    REM //Retrieve file name without .dxf extension
    SET NAME=%%~ni
)
pause
REM //The line bellow needs to be done outside the for loop for some reason...
SET PAGE=%NAME:~10%
pause
REM // Rename file to standard file name
REN c:\dxf\in\drw*.dxf %PART_NUMBER%_drw%PART_NUMBER%%PAGE%%REVISION%_dxf.dxf
REM // Move the renamed .dxf to the C:\dxf\out\ folder
MOVE /Y "C:\dxf\in\*.dxf" "C:\dxf\out\"
REM // clean up in folder of *.txt and *.log files
DEL "C:\dxf\in\*.txt"
DEL "C:\dxf\in\*.log*"
exit

根据您的描述-您似乎只需要在实际文件名中添加前缀和后缀,并保留扩展名。在这种情况下,通过更新代码的相关部分,您可以相对轻松地做到这一点:

REM Add this to the top of your script.
SETLOCAL EnableDelayedExpansion

REM Other code goes here...

REM Use the DIR command output so files to process are loaded in memory.
FOR /F "usebackq tokens=* delims=" %%i IN (`DIR "C:\dxf\in\*.dxf" /B`) DO (
    SET NAME=%%~ni
    SET Extension=%%~xi
    REM Rename the file by prefixing with the part number and suffixing with the revision.
    RENAME "%%~fi" "%PART_NUMBER%!NAME!%REVISION%!Extension!"
)

REM Other code goes here...

REM Add this to the end.
ENDLOCAL

SETLOCAL EnableDelayedExpansion
允许您使用在每个循环迭代的上下文中设置的变量。由于您的脚本中没有指定此项,因此
NAME
变量仅在循环外部可用。

非常感谢您提供的信息!我最终让它工作了。我将添加SETLOCAL EnableDelayedExpansion以在循环中获取名称。