.BAT file to move files into folders and subfolders by filename… can't get subfolders to work

倖福魔咒の 提交于 2019-12-24 10:50:46

问题


I just can't figure this out.

I have a bunch of files with name format: "PREFIX_PREFIX2_filename.pdf"

I want to sort them into folders like this: "PREFIX/PREFIX2/(files)"

This is what I have so far:

setlocal enableextensions disabledelayedexpansion

for %%f in (*_*_*.pdf, *_*_*.png) do (
    for /f "tokens=1, 2 delims=_" %%p in ("%%~nf") do (
        for %%d in ("%%~dpf.") do if /i not "%%~p"=="%%~nd" (
            if not exist "%%~dpf\%%~p"  md "%%~dpf\%%~p"
            if not exist "%%~dpf\%%~p"  md "%%~dpf\%%~p"
            move "%%~ff" "%%~dpf\%%~p"
        )
    )
)

This sorts them based on the first prefix, but I just can't get any further, and honestly I am not sure even sure what's going on here anyway. This CMD language has got to me the most ugly and inscrutable thing I've ever seen.

I have read over a bunch of similar questions but still couldn't work it out.

I would be very grateful if someone could advise me how to finish up this surely relatively simple task and also explain to me what the hell is going on here.


回答1:


This method is simpler:

setlocal

for /F "tokens=1,2* delims=_" %%a in ('dir /B *_*_*.pdf *_*_*.png') do (
   if not exist "%%a" md "%%a"
   if not exist "%%a\%%b" md "%%a\%%b"
   move "%%a_%%b_%%c" "%%a\%%b\%%c"
)

That is: dir /B *_*_*.pdf command produce a list of names with PREFIX_PREFIX2_filename.pdf format. for /F "tokens=1,2* delims=_" %%a divide such names in 3 tokens this way: %%a=PREFIX, %%b=PREFIX2 and %%c=filename.pdf. The rest is obvious...

PS - I suggest you to change the sort word in your title to move. The first term gives the idea of an entirely different task...



来源:https://stackoverflow.com/questions/29064099/bat-file-to-move-files-into-folders-and-subfolders-by-filename-cant-get-sub

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