.bat file sorting files into folders

2020-04-01 23:48发布

For my picture collection I want to have all pictures in a folder automatically sorted into folders by date. Luckily the files are already named after the timestamp:

  • 2012-07-15 12.21.06.jpg
  • 2012-07-15 12.21.26.jpg
  • 2012-07-16 17.12.50.jpg

In this example the two first files should end up in a folder 2012-07-15, the third one in 2012-07-16. I've tried and googled, all I can find is this:

for %%a in (*.jpg) do (
    md "%%~na" 2>nul
    move "%%a" "%%~na"
)

But that makes a folder for every file name. I thought of having a variable that has the ten first chars, but get totally confused and frustrated with variable declaration and use in dos. Can anyone help?

2条回答
孤傲高冷的网名
2楼-- · 2020-04-02 00:02

Here's another possibility how you could do this using delayed expansion and substrings:

SETLOCAL ENABLEDELAYEDEXPANSION
for %%a in (*.jpg) do (
    set f=%%a
    set g=!f:~0,10!
    md "!g!" 2>nul
    move "%%a" "!g!"
)

The first line enables the syntax using ! instead of % and has the effect to interpret the value of the variable not as the first line of the block is executed (standard batch behavior), but only when the line itself is executed.

!f:~0,10! is the syntax to obtain a substring - the dates you're after are always 10 characters long.

查看更多
霸刀☆藐视天下
3楼-- · 2020-04-02 00:18

use the output from a dir command so you can split the filename at the space

for /f "tokens=1* delims= " %%a in ('dir /b *.jpg') do (
    md %%a 2>nul
    move "%%a %%b" %%a
)   

to try to clarify the for statement:
the /f in the for allows us to process the output of the dir command.
The tokens=1* tells dos that we want the first part before the space to be put in %%a, and the rest of the filename in %%b (you can use other options for tokens, and it will put the parts into subsequent letters, up to a maximum of 26 parts)
the delims= states we want space as the delimiter between the parts.

so, for the first list, 2012-07-15 12.21.06.jpg it would put 2012-07-15 into %%a and 12.21.06.jpg into %%b when we do the move we have to put the space back in, as it was stripped out when it was split into parts, so we have to use %%a %%b instead of %%a%%b

查看更多
登录 后发表回答