How To Merge Folders With Similar Names With A Batch File

0

I amm Trying to write a command that can merge all folders inside a directory that have similar names. Now all these folders are uniquely named so I am thinking you can base the "similar name" concept off the first 5 characters of the folders.

folder will look like

longyellowbus-092092301
longyellowbus-92382012
5fatmimn-324535232
hintout-239119393
hintout-2391038949
hintout-2983419101
dogscats-293457893
2dummerboy-9293982
2dummerboy-29848292

and I would like to merge all the folders that have similar names into one folder and some of the content inside will be the same so it is OK to overwrite. So basically the end result will look like.

longyellowbus-092092301
5fatmimn-324535232
hintout-239119393
dogscats-293457893
2dummerboy-9293982

The numbers on teh end after the dash - doesn't matter in fact I am gonna try and delete them after the merge so all that is left is clean folder names only.

longyellowbus
5fatmimn
hintout
dogscats
2dummerboy

I got stump and hope you guys can help. This is just part of a larger command I have been writing and this is the part I got stumped on.

Juan Lopez

Posted 2017-01-09T02:04:38.570

Reputation: 33

Please note that https://superuser.com is not a free script/code writing service. If you tell us what you have tried so far (include the scripts/code you are already using) and where you are stuck then we can try to help with specific problems. You should also read How do I ask a good question?.

– DavidPostill – 2017-01-09T11:28:47.677

Answers

0

The following batch parses the output of the dir by splitting the dir names at the delimiter -, %%A being the first token and %%B the remainder. If a dir like the first token doesn't exist it is renamed, if it does the content of the long-named dir is forcibly moved and the dir removed afterwards.
Edit the path to suit your environment.

@Echo off
pushd "C:\path\to\your\base\folder"
for /f "Tokens=1* Delims=-" %%A in (
  'Dir /B /AD *-*'
) Do If Not Exist "%%A" (
  Ren "%%A-%%B" "%%A"
) Else (
  Move /Y "%%A-%%B\*" "%%A\"
  RmDir "%%A-%%B"
)
PopD

LotPings

Posted 2017-01-09T02:04:38.570

Reputation: 6 150