Moberg
Moberg

Reputation: 33

folders containing spaces loop

Im stuck, have tried everything I can come up with but no luck. Have read about usebackq but can't get that to work.

Im trying to create a batch file. is supposed to check if a folder1 exists. If it do exists the batch file is supposed to create folders called Batch_1 Batch_2 inside folder1. Move all files in folder1 to Batch_1 and then move files from someplace to batch_2.

And if batch_2 exists it shold create Batch_3 and then move files from someplace to batch_3. And so on.

This is what I have so far. Works like a charm when there are no spaces in the paths...

@echo off &setlocal

set fullDest="C:\Users\Peppes Bodega\Desktop\hej hej\123"
set fullDest=%fullDest:"=%


if exist "%fullDest%" goto:omg2
echo %fullDest%

:omg1
echo normal flytt syntax
pause
goto:eof

:omg2
if exist %fullDest%\Batch_2 goto:omg3
for /d %%i in (%fullDest%) do (
    pushd %%i\
    set /a count=0
    for /d %%j in (*.*) do set /a count+=1
    popd
    call echo %%count%% folder(s^) in %%i
    call mkdir %fullDest%\Batch_%%count%%
    call MOVE C:\Users\%username%\Desktop\_BP_TEMP\*.txt %fullDest%\Batch_%%count%%
    pushd %%i\
    set /a count=0
    for /d %%j in (*.*) do set /a count+=1
    popd
    call mkdir %fullDest%\Batch_%%count%%
    call MOVE C:\Users\%username%\_BP_TEMP\*.txt %fullDest%\Batch_%%count%%
)
pause
goto:eof
:omg3
for /d %%i in (%fullDest%) do (
    pushd %%i\
    set /a count=0
    for /d %%j in (*.*) do set /a count+=1
    popd
    call mkdir %fullDest%\Batch_%%count%%
    call MOVE C:\Users\%username%\Desktop\_BP_TEMP\*.txt %fullDest%\Batch_%%count%%
)
pause
goto:eof

I would be so greatful for a helping hand.cr

Upvotes: 0

Views: 45

Answers (1)

Magoo
Magoo

Reputation: 80033

First let's clear up a little awkward syntax.

set fullDest="C:\Users\Peppes Bodega\Desktop\hej hej\123"
set fullDest=%fullDest:"=%

is better as

set "fullDest=C:\Users\Peppes Bodega\Desktop\hej hej\123"

The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned. set /a can safely be used "quoteless".

Next, for /d lists directories if the target contains wildcards so you need

for /d %%i in ("%fullDest%\*") do (

equally, wherever you use fulldest you need to enclose the name in quotes to ensure that it is regarded as a single item, not a list, hence

if exist "%fullDest%\Batch_2" goto:omg3

(similar to your initial use)

call MOVE "C:\Users\%username%\Desktop\_BP_TEMP\*.txt" "%fullDest%\Batch_%%count%%"

(move requires move source destination - quotes as shown tell cmd that each element may contain spaces)

similarly,

call mkdir "%fullDest%\Batch_%%count%%"

and so on.

The closing \ in your pushds are superfluous.

Upvotes: 1

Related Questions