MacOS – Terminal command to move all loose files into a directory with the file name

command linefindermacosscript

I have a folder containing thousands of files and directories. I would like to move all the files that are not contained in a sub directory into a directory and name it the file name, while leaving the files already inside of directories alone, ie:

  • create 'newdir'
  • move 123.mp4 into 'newdir'
  • change name 'newdir' to '123'
  • repeat

Best Answer

Command

This command was tested in a bash shell.

for x in *;do if [[ -f $x ]];then mkdir newdir;mv "$x" newdir/.;mv newdir "${x%.*}";fi;done

Explanation

The code shown below is not necessary commands you can execute. Rather, what is shown is an explanation of various parts of the code shown above.

Loop through all file names in current directory.

for x in *;do ... done

Only do regular files. (Skip the directories.)

if [[ -f $x ]];then ... fi;

Make new directory newdir.

mkdir "newdir";

Move file x to new directory newdir.

mv "$x" newdir/.;

Rename newdir to the name of the desired new directory. (Set newdir to file name x after removing the last . and all characters that follow.)

mv newdir "${x%.*}";

Comments

If the desired directory already exists, then the newdir folder (containing the file) will be moved to the desired directory. For example, if the file 123.mp4 and directory 123 both already exist, then file 123.mp4 will end up in 123/newdir. You can test to see if this occurred by entering the command given below.

find . -name newdir

For example, if 123/newdir/123.mp4 existed, then the follow output would appear.

./123/newdir