Mahmoud S. Marwad
Mahmoud S. Marwad

Reputation: 244

Moving files from more than one folder to the parent directory using CMD

I have a folder Target contains multiple folders,

each folder contains one file with the same name of the folder

target folder

one of siblings folders

I want to move the files in folders Part1,Part2,Part3,Part4 and Part5

to parent folder ("Target" in this case) using cmd then delete the folders.

The result should be like that :

result

In Linux i could've used mv Part*\*.* ..

I've tried copy "Part*\*" "" command, but it doesn't work.

Upvotes: 1

Views: 1432

Answers (2)

aschipfl
aschipfl

Reputation: 34899

In the Windows Command Prompt, copy "Part*\*" "" cannot work, because wildcards are only permitted in the last element of a path but not somewhere in the middle.

To work around this, use a for /D loop to resolve wildcards in Part*, then let copy deal with the remaining ones:

for /D %I in ("Part*") do @copy "%~I\*" ".."

To move the files rather than to copy, simply replace copy by move. If you want to remove empty sub-directories then, append rd using &&:

for /D %I in ("Part*") do @move "%~I\*" ".." && @rd "%~I"

To use the above code fragments in a , ensure to double all the %-signs.

Upvotes: 0

shadow2020
shadow2020

Reputation: 1351

Use a For loop. The key to getting directory names in this code is "dir /a:d" which only lists directories. I put that into the %%a variable. Use %~dp0 to refer to the directory the batch file is in. If your bat is somewhere else, do a find and replace all for that to the directory path you need. Lastly use RMDIR to remove each folder with /q /s to make it silent and remove all files within the directory (part1 part2 etc...) and the directories themselves.

@echo off
for /f "tokens=* delims=" %%a in ('dir /a:d /b "%~dp0"') do (
        copy "%~dp0%%a\*.*" "%~dp0"
        RMDIR /q /s "%~dp0%%a"
        )

Upvotes: 1

Related Questions