Batch to create folders and move files

April 10, 2010 at 20:54:56
Specs: Windows XP
Trying to write a batch to create directories based on a partial filename, and then move files into their directory.

Files look like this:

artist - title - abc123.mp3
artist - title - abc123.cdg
artist - title - xyz123.mp3
artist - title - xyz123.cdg


Folder should be "abc123" and "xyz123" and both files should be moved there. Each directory has 10-20 files in 'pairs' like shown above. I would like to run the batch directly from the directories.

Using the batch below - I'm not a coder so it is rough - the directories are created, but an error is generated and the files are not moved.

echo off
setlocal enabledelayedexpansion
for /f "tokens=3 delims=-" %%a in ('Dir /b /a-d *.mp3') do (
md %%~na
echo move %%~nxa \%%~na
)

Thanks for looking.


See More: Batch to create folders and move files

Report •


#1
April 10, 2010 at 21:05:50
relative vs absolute paths? also might need quotes:
echo move %%~nxa \%%~na
might try:
move "%%~nxa" "%%~na"
::
or:
move "%%~nxa" ".\%%~na"

Report •

#2
April 10, 2010 at 21:18:44
those didn't work. One issue is that in order to get the folder names the way I want, I use
"tokens=3 delims=-"

so the variable %%~nxa is now only the folder name, so it does not find the file to move.

Report •

#3
April 10, 2010 at 21:22:56
In another post I found this:

@echo off & setLocal EnableDELAYedExpansion

for /f "tokens=* delims= " %%a in ('dir/b/a-d *.txt') do (
set dname=%%~Na
set dname=!dname:~0,7!
if not exist !dname! md !dname!
move %%a !dname!
)

Which would work if I change it to create the folders using the third token with a hyphen delimiter (instead of the first 7 characters as written above).


Report •

Related Solutions

#4
April 10, 2010 at 21:48:10
ah, i see said the blind man... good point.
maybe try "reconstructing" the filename from the scraps:
for /f "tokens=1-3 delims=-" %%a in ('Dir /b /a-d *.mp3') do (
md %%~nc
echo move "%%a-%%b-%%c" \%%~na
)

Report •

#5
April 10, 2010 at 22:42:01
Getting close...

Here's the code:

echo off
setlocal enabledelayedexpansion
set _source=%inpath%
for /f "tokens=1-4 delims=-" %%a in ('Dir /b/a-d *.*') do (
md "%%~nc"
move "%%a-%%b-%%c-%%d" "%%~nc"
)

FYI there are four tokens. So this is working, creates the folders, and copies the mp3 and cdg files to the correct directory. Yea! I am getting a 'directory already exists' and 'there are no more files' errors. So maybe add some error checking and we'll be golden.


Report •

#6
April 10, 2010 at 22:53:31
Final code - works great! Thanks for the assist nbrane.

echo off
setlocal enabledelayedexpansion
for /f "tokens=1-4 delims=-" %%a in ('Dir /b/a-d *.*') do (
if not "%%~fa"=="%~f0" (
md "%%~nc" 2>nul
if exist "%%c" move "%%a-%%b-%%c-%%d" "%%~nc"
)
)


Report •

Ask Question