Dunc
Dunc

Reputation: 1

Creating Windows batch file to create folder/ files

I would like to create folders from a prefix of certain file then copy multiple files with a certain string in their file name to that folder. For example:

VI files to a folder called DM0008 with the following files

DM0008d3VI_001.IMI
DM0008d3VI_002.IMI

MI files to a folder called DM0008MI with the following files

DM0008d6MI_002.IMI
DM0008d6MI_003.IMI

I did try this but this created a folder for each individual file:

@echo off
for %%a in (*VI*) do (
  md "%%~na" 2>nul
  move "%%~na.*" "%%~na"
)
for %%a in (*MI*) do (
  md "%%~na" 2>nul
  move "%%~na.*" "%%~na"
)

Upvotes: 0

Views: 371

Answers (3)

LS_ᴅᴇᴠ
LS_ᴅᴇᴠ

Reputation: 11191

If your only directories to use are DM0008 and DM0008MI and your file patterns are DM0008d3VI_*.IMI and DM0008d6MI_*.IMI then:

@ECHO OFF
IF EXIST DM0008d3VI_*.IMI (
    MD DM0008
    MOVE DM0008d3VI_*.IMI DM0008
)
IF EXIST DM0008d6MI_*.IMI (
    MD DM0008MI
    MOVE DM0008d6MI_*.IMI DM0008MI
)

If this is not your specification, please, make it clearer is your question.

Upvotes: 0

Endoro
Endoro

Reputation: 37589

@ECHO OFF &SETLOCAL
FOR /f "delims=" %%a IN (file) DO (
    FOR /f "delims=" %%b IN ('echo("%%~na"^|sed -r "/VI/s/(..[0-9]+).*/\1/;/MI/s/(..[0-9]+).*/\1MI/"') DO (
        ECHO MD "%%~b" 2>NUL
        ECHO MOVE "%%~fa" "%%~b"
    )
)

sed for Windows

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200533

Assuming that the first part of the file name (DM####) will always be 6 characters long you could do this:

@echo off

setlocal EnableDelayedExpansion

for %%a in (*VI*) do (
  set "folder=%%~na"
  set "folder=!folder:~0,6!"
  if not exist "!folder!" md "!folder!"
  move "%%~nxa" "!folder!"
)
for %%a in (*MI*) do (
  set "folder=%%~na"
  set "folder=!folder:~0,6!MI"
  if not exist "!folder!" md "!folder!"
  move "%%~nxa" "!folder!"
)

Upvotes: 1

Related Questions