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

时间:2015-01-26 17:49:05

标签: batch-file

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

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

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

我需要将其更改为1234567_drw1234567_1Rev0A.dxf

我已经能够创建" REVISION"和" PAGE"我的脚本中的参数,但无法获得" PART_NUMBER"。任何帮助将不胜感激!

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

1 个答案:

答案 0 :(得分:0)

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

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变量仅在循环外可用。