Fix last-but-one space-separated words to move files

Viewed 53

I try to move files making with a script their respective folders.
Example of desidered and wrong output

enter image description here

To set a substring I use

for %%I in (*.cbr) do (

   set "file=%%I"
   for %%J in ("!file: =\!") do set "folder=!file: %%~nxJ=!"

For example if I have this filenames

the punisher one.cbr
the punisher two.cbr

the folder name will be the punisher

Problem is when I try to move with another example. If I have 3 files

the punisher beta.cbr
the punisher beta new.cbr
the punisher past.cbr

and I use this command to make directories

mkdir "!folder!" 2>NUL
   move /Y "!file!" "!folder!"

But with this example is where I fail and I get unwanted outcome because it creates 3 folders instead of only one (it wrongly also move all files when should be move only 2 files in one folder)

Where is the mistake? I don't understand if is here

for %%J in ("!file: =\!") do set "folder=!file: %%~nxJ=!"

or here

mkdir "!folder!" 2>NUL
       move /Y "!file!" "!folder!"

Entire code example is

@echo off
setlocal EnableDelayedExpansion

for %%I in (*.pdf) do (

   set "file=%%I"
   for %%J in ("!file: =\!") do set "folder=!file: %%~nxJ=!"

   mkdir "!folder!" 2>NUL
   move /Y "!file!" "!folder!"
   echo "!file!" moved to "!folder!"

)
0 Answers
Related