Script to create folder with same name as file and move file into folder

Before you start, I really recommend you make a backup of the folder you are trying to do this on.

cd into the folder you trying to operate on and then:

for file in *; do
  if [[ -f "$file" ]]; then
    mkdir "${file%.*}"
    mv "$file" "${file%.*}"
  fi
done
  1. Loop over all (*) the files in the current folder.
  2. create a folder (mkdir) from the file without its extension ${file%.*}
  3. move (mv) the file into that folder.

Note that you have to use quotation because some files might have spaces in their names.

You can either type this up in the terminal or creating a script file.


I don't have enough reputation to add this as a comment to @Ammar Alammar's awesome answer above, but in case anyone wants to just paste this directly at a terminal prompt rather than saving it as a script, this one-liner should do the trick:

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