Script to create folder with same name as file and move file into folder
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.
Solution 1:
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
- Loop over all (
*
) the files in the current folder. - create a folder (
mkdir
) from the file without its extension${file%.*}
- 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.
Solution 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