简体   繁体   中英

batch file to create directory based on file name, move like files to new directory

I have hundreds of files in a directory that all have different names but some of those are related.

The files are mostly.AI and PDF and are all names like this:

  • FILE1_retail_xxx.ai
  • FILE1_label_xxx.ai
  • FILE2_retail_xxx.ai
  • FILE2_label_xxx.ai
  • FILE3_retail_xxx.ai
  • FILE3_label_xxx.ai

What I want to do is have a batch file create directories for FILE1, FILE2, FILE3, etc. and move all files that start with FILE1, FILE2, FILE3, etc. into those newly created directories.

I have used this, but it just makes a DIR for the whole filename.

@echo off
for %%i in (*) do (
 if not "%%~ni" == "organize" (
  md "%%~ni" && move "%%~i" "%%~ni"
 )
)

This doesn't do what I need, can anyone help massage this into what I need or give me a new batch file to try?

Thanks! This will save me countless hours of manual work!

You need to split the filename by _ with another for /f loop:

@echo off
for %%i in (*) do (
  if not "%%~ni" == "organize" ( 
    for /f "delims=_" %%a in ("%%~ni") do (
      md "%%a" 2>nul 
      move "%%~i" "%%~a\" 
  )
)

2>nul suppresses the error message in case the folder already exists.

Please consider using for %%i in (*_*) do ( or for %%i in (*_*_*.ai *_*_*.pdf) do ( - according to your actual needs/file names to pre-select files to be moved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM