MacOS – Move files to individual folders, using file name as folder naming convention for folder, using Terminal

macosscriptterminal

I've been looking for answer on the web now for a few hours and can't find what im looking for. What i want to do is move each file in a directory to a new folder using the name of the file, excluding the extension.

/Movies/Filname.avi —> /Movies/Filename/Filename.avi

I know how to do each individual file, but can i do it reclusively for the whole folder using one command or a script.

Best Answer

This should do the trick.

#!/bin/bash
shopt -s nullglob    #avoid problems in directory with no files
ext=avi              #the file extension to search for
for f in *.$ext; do
    d="${f##/}"      #gives us just the filename
    d="${d%.$ext}"   #strips the file extension
    mkdir "$d"       #makes the directory
    mv "$f" "$d/$f"  #moves the file
done