1

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.

Xenthide
  • 79
  • 7
  • `for %f in (*_*_*.*) do @for /f "tokens=1,2* delims=_" %p in ("%~nf") do @echo %~ff %~dpf%p\%q\%r%~xf` Run previous example from command line, could help. To use in a batch script, double all `%` signs. IMHO you are on a good way... – JosefZ Mar 15 '15 at 18:13

1 Answers1

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...

Aacini
  • 65,180
  • 12
  • 72
  • 108
  • Ah, many thanks, that did it. I was trying to work out what was going on from some similar scripts in other questions here and just couldn't get the hang of the notation. One thing though, I did have to make a slight change before it worked - should be `for /f "tokens=1,2* delims=_" %%a in ...` I think. Other than that works great. I will change the title also now as you have suggested. – Xenthide Mar 15 '15 at 19:56