简体   繁体   中英

Renaming a batch file and keeping part of the filename

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM