Create folders according to file names

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
ice552
Posts: 2
Joined: 27 Oct 2017 11:31

Create folders according to file names

#1 Post by ice552 » 27 Oct 2017 11:44

Hello,

I know that this is similar topic to another ones, but I need exact code for specific situation. Hope somebody can help me.
I need to create folder's from file name and after that move to them.
I have files in this format:

xxxx_xxxxxx_xxxxx_abcd.xls
xxxx_xxxxxx_xxxxxxx_xxxx_efghi.doc
xxxx_xxxxxx_xxxxxx_hjiltj.xls
xxxx_xxxxx_xxx_xxxxx_tlmiuuuu.txt

Structure should be:
abcd\xxxx_xxxxxx_xxxxx_abcd.xlsx
efghi\xxxx_xxxxxx_xxxxxxx_xxxx_efghi.doc
hjiltj\xxxx_xxxxxx_xxxxxx_hjiltj.xls
tlmiuuuu\xxxx_xxxxx_xxx_xxxxx_tlmiuuuu.txt

Folder should be created from last character's before first "_"

Thank you very much

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Create folders according to file names

#2 Post by aGerman » 27 Oct 2017 12:24

Customize the path after PUSHD to where your files are saved.

Code: Select all

@echo off &setlocal

pushd "C:\somewhere\xyz"

for %%i in (*.*) do (
  set "file=%%~i"
  set "name=%%~ni"
  call :moveFile
)

popd

exit /b


:moveFile
set "name=%name:_=" & set "name=%"
md "%name%"
move "%file%" "%name%\"
exit /b

Steffen

ice552
Posts: 2
Joined: 27 Oct 2017 11:31

Re: Create folders according to file names

#3 Post by ice552 » 27 Oct 2017 13:14

Hi Steffen,

this work almost perfectly, thank you very much.

Could you please let me know how to update path to reflect this scenario?

I have this batch file copied in xxx folder with all of these files and I do not want to set path, only copy batch file where are other files and run.

I tried set path as pushd "%cd%"
but this will only copy batch file to folder same as batch file and other files are sill untouched.

Thank you

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Create folders according to file names

#4 Post by aGerman » 27 Oct 2017 13:20

If possible you should place the script somewhere else because it will process itself otherwise.

If that's not an option then you could change the CALL line to

Code: Select all

  if "%%~i" neq "%~nx0" call :moveFile
Also you don't need PUSHD and POPD anymore.

Steffen

Post Reply