Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

1 Answer 1

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.

share|improve this answer
3  
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
1  
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

 
discard

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.