Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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)?

share|improve this question

Try this snippet, assuming all you've got in the currently directory is files (no directories):

for file in *
  mv "$file" "$file".tmp &&
  mkdir "$file" &&
  mv "$file".tmp "$file"/"$file"

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.

share|improve this answer
You 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 Jul 16 '11 at 18:56
Very 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 1:42

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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