Reputation: 23
I was trying to move my files(books) based on it's author name. For example:
[author] Title 1.pdf
[author2] Title A.pdf
I've found a batch script for this
@echo off
for %%i in (*) do (
if not "%%~ni" == "organize" (
md "%%~ni" && move "%%~i" "%%~ni"
)
)
It works but it made each folder for each files, what I want to do is create folder by author names and move it there.
Note: All author name have "[]" in it's file name but the folder created only has author name without "[]".
Please help, I have 4000+ files I need to sort.
Upvotes: 0
Views: 846
Reputation: 34899
The following script uses a for /F
loop to split the file names which are gathered by the dir
command:
@echo off
for /F "tokens=1* delims=[] eol=]" %%I in ('dir /B /A:-D-H-S "[*]*.pdf"') do (
ECHO md "%%I" 2> nul
ECHO move "[%%I]%%J" "%%I\"
)
The 2> nul
portion suppresses error messages in case the directory to create already exists.
After having tested for the correct output, remove the upper-case ECHO
commands from the md
and move
command lines. To avoid multiple 1 file(s) moved.
messages, append SPACE + > nul
to the move
command line.
The trailing \
at the destination of the move
command is intended to force it to point to a directory. Imagine the destination directory could not be created for some reason (for example, lack of access privileges), the destination without the \
is interpreted as a new file name in the working directory, leading to unintentional renaming; with the \
the move
command expects an existing directory, and if not found an error arises.
Besides the fact that your code did not attempt to split the file names as needed, there is one additional problem: the &&
operator lets the following command execute only in case of success of the former one; so when md
failed, move
does not run. For example, you have got two files with the same author, so when iterating the second one, the destination directory already exists since it has been created in the previous iteration, so md
fails and the respective file is not moved. Therefore you should have used the unconditional &
operator.
Upvotes: 3