8

I have lots of individual files:

/File 01.txt /Picture 02.png

Is there a terminal command that would do this so I end up with this:

/File 01/File 01.txt /Picture 02/Picture 02.png/

I'm on a Mac in OS X 10.11.3

It sounds very simple, but I'm fairly new to Mac's and have no real knowledge of Terminal having moved from Windows.

10

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.

| improve this answer | |
  • AMAZING! Thanks sooo much. Is it possible to get the loop to only loop over files and ignore any existing directories? – neildeadman Mar 5 '16 at 22:07
  • I should add it works with this, but causes an error when it processes each directory. – neildeadman Mar 5 '16 at 22:45
  • 1
    That's easy! You just need an if statement that tests if $file is a folder or a file. I edited my answer to reflect that. – Ammar Alammar Mar 6 '16 at 11:57
  • Superb script. This just saved me hours of time. I was able to cd into my folder in Terminal and just copy/paste the script and hit return for it to work. – GForce Jul 27 '19 at 16:20
2

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
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.