Bat to Prefix File names with folder characters & suffix with date

你。 提交于 2019-12-25 03:52:43

问题


I'm a complete newbie when it comes to bat/cmd stuff. I can do the very very basics with a little help from google! & when i mean basic im talking xcopy, robocopy etc.

I am trying to write a code that will extract the 1st 5 characters from the current folder & rename files within a subfolder but also suffix with the current date.

So this is basically what im trying to do.

W:\12345_folder This is the main folder that I want to extract the 12345 from.

W:\12345_folder\subfolder This is the location for the files that are to be renamed

Current name of files within subfolder are as follows

file1.txt file2.txt file3.txt

After renaming they should be as below

12345 file1 2014-10-02.txt 12345 file2 2014-10-02.txt 12345 file3 2014-10-02.txt

All my efforts have been in vain. I can get the date using this. But it renames the whole filename & does not retain the existing filename.

for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "*.txt" %%g%%f-%%e-%%d.txt

And I have also been playing with this:

for %%z in ("%cd%") do ( for %%a in ("%%~dpz%\.") do ( rename "**.txt" "%%~nxa-.txt"))

But again this overwrites the whole filename and does not retain the existing file name.

I must stress once again I am a complete novice so be gentle & your help is greatly appreciated.


回答1:


The problem appears to be with the RENAME command in Windows has some bugs, specifically with assigning prefixes and suffixes (see bottom link).

I only did part of the answer because I wasn't able to get date working as a suffix. But, this will allow you to prefix filenames in a directory with the prefix of your choosing, including the date.

I tried to get a "date as a suffix" solution working, but I had no success with the following on my version of cmd:

    REN *.txt ????????????????abc.txt.x
    REN *.x *

Returns: Invalid name

Here is my alternate solution, to add a prefix date. For your first batch example, create two batch files:

renprefix.bat

    %4
    FOR %%v IN (%1) DO CALL %0 %1 %2 %%v GOTO:Part2
    ATTRIB -h %2%1
    GOTO End
    :Part2
    REN %3 %2%3
    ATTRIB +h %2%3
    :End

Then, use the above batch file in your example:

rendate.bat

    for /f "tokens=1-5 delims=/ " %%d in ("%date%") do renprefix.bat *.txt %%g%%f-%%e-%%d

Source: http://www.lagmonster.org/docs/DOS7/z-ren1.html "4. Adding a prefix"



来源:https://stackoverflow.com/questions/26165578/bat-to-prefix-file-names-with-folder-characters-suffix-with-date

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