Renaming a batch file and keeping part of the filename

流过昼夜 提交于 2019-12-13 04:46:43

问题


I've seen plenty of posts on similar requests but I can't quite find one that suits what I am trying to do. It is fairly simple but I cannot seem to get it.

ren FILE??.txt FILE%Year%%Month%%Day%??.txt


copy FILE%Year%%Month%%Day%??.txt C:\Users\me\Desktop\Batch\renamed\achod%Year%%Month%%Day%??.txt

I cannot get the script to keep the '??' which represents random characters the first file may have.

Any help is appreciated.


回答1:


You won't be able to rename files directly using a wildcard character. Instead you need to locate all the applicable files and then rename each.

The script below works under the assumptions of your question/comments:

  • File name is 6 chars long.
  • Only the last 2 chars are interchangeable.

Of course, the script could be very easily adapted to accomodate other settings but this does just as you requested.

SETLOCAL EnableDelayedExpansion

REM Set your Year, Month, Day variable values here.
REM They will be used for file renaming.
...

CD "C:\Path\To\Files"

FOR /F "usebackq tokens=* delims=" %%A IN (`DIR "File??.txt" /B /A:-D`) DO (
    REM Extract the last 2 chars of the file name.
    SET FileName=%%~nA
    SET First4=!FileName:~0,4!
    SET Last2=!FileName:~-2!

    REM Rename the file, inserting the new data.
    RENAME "%%A" "!First4!%Year%%Month%%Day%!Last2!%%~xA"
)
ENDLOCAL


来源:https://stackoverflow.com/questions/27806085/renaming-a-batch-file-and-keeping-part-of-the-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!