Is there any way on a linux box to move every file in a directory into their own sub directory (i.e. make a directory named after it and move it in)?
Asked
Active
Viewed 842 times
1 Answers
7
Try this snippet, assuming all you've got in the currently directory is files (no directories):
for file in *
do
mv "$file" "$file".tmp &&
mkdir "$file" &&
mv "$file".tmp "$file"/"$file"
done
Otherwise (tested only lightly):
find . -maxdepth 1 -type f -exec mv '{}' '{}'.tmp \; -exec mkdir '{}' \; -exec mv '{}'.tmp '{}'/'{}' \;
This worked on my test directory with a couple of arbitrarily named files, some of them with spaces.

Eduardo Ivanec
- 14,881
- 1
- 37
- 43
-
3You need double quotes around variable substitutions, otherwise your snippet will go haywire if any file name contains whitespace or wildcards. You can't do that in your second snippet using `find`; you'll need to use `find … -exec`. – Gilles 'SO- stop being evil' Jul 16 '11 at 18:56
-
1Very true! It's the kind of thing I forget over and over again, probably because I don't have many filenames with spaces on them. Thanks! – Eduardo Ivanec Jul 17 '11 at 01:42