Dizzy49
Dizzy49

Reputation: 1520

Need a script to create folders based on file names, and auto move files

I need a batch file (for Windows) that I can run that will take a (very) large number of files, and place them in their own folders.

The source directory has a structure as follows:

\\Movies\Movie1.mkv
\\Movies\Movie1.idx
\\Movies\Movie1.sub
\\Movies\Movie1.jpg
\\Movies\Movie1.mkv_sheet.jpg

\\Movies\Movie2.mkv
\\Movies\Movie2.idx
\\Movies\Movie2.sub

\\Movies\Movie3.mkv
\\Movies\Movie3.idx
\\Movies\Movie3.sub

I need it to create a folder based on the mkv file name, and then move Movie*.* into that folder so it looks like this:

\\Movies\Movie1\Movie1.mkv
\\Movies\Movie1\Movie1.idx
\\Movies\Movie1\Movie1.sub
\\Movies\Movie1\Movie1.jpg
\\Movies\Movie1\Movie1.mkv_sheet.jpg

\\Movies\Movie2\Movie2.mkv
\\Movies\Movie2\Movie2.idx
\\Movies\Movie2\Movie2.sub

Upvotes: 1

Views: 7961

Answers (2)

Rob Evans
Rob Evans

Reputation: 6968

Anyone looking for the same thing on Linux / MacOS, this should do the job:

#!/bin/bash

# Specify the source folder
source_folder="/path/to/source/folder"

# Check if the source folder exists
if [ ! -d "$source_folder" ]; then
  echo "Source folder does not exist."
  exit 1
fi

# Move to the source folder
cd "$source_folder" || exit 1

# Iterate through each file in the source folder
for file in *; do
  # Check if it's a file, not a directory
  if [ -f "$file" ]; then
    # Extract the file name without extension
    file_name="${file%.*}"
    
    # Create a new folder with a unique identifier
    folder_name="$file_name"
    mkdir -p "$folder_name"
    
    # Move the file into the new folder
    mv "$file" "$folder_name/"
    
    echo "Moved $file to $folder_name/"
  fi
done

echo "Organizing files complete."

Make sure you change your source_folder="/path/to/source/folder" at the top of the file to the folder you wish to operate on. I've tested this on MacOS with the folder pointing to a mounted network volume on a NAS and it works no problem.

On MacOS, if you mount a network folder you can find the path under the /Volumes folder.

Upvotes: 0

dbenham
dbenham

Reputation: 130839

Edited to use path specified in comment

@echo off
pushd D:\Video
for %%F in (*.mkv) do (
  2>nul md "%%~nF"
  >nul move /y "%%~nF*.*" "%%~nF"
)
popd

Upvotes: 3

Related Questions