Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. 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

This might sound like something quite odd but for my HTPC, I need to rearrange how my files are stored such that each of the individual files in a folder needs to be moved to a subdirectory of its own (with the same name as the file).

I.E. - Currently the directory is:

- a.file
- b.file
- c.file

and I want to change it to:

- a/
-- a.file
- b/
-- b.file
- c/
-- c.file

I don't think this is terribly tricky but it's just odd and I haven't found anybody doing it before: I think it can be done with find and exec but I'm a bit of a battler and can't quite get it.

Thank you very much in advance (or even just for taking the time to read this).

share|improve this question
Always the same extension? – Hauke Laging Jul 1 '13 at 2:19
No, but all the files in the folder I want this done too. Also, there's only 3 or so file extensions so if you know a way of doing it for the same extension, I could just run the command thrice, changing the extension each time: it's not a huge concern. – paddymelon Jul 1 '13 at 2:22
up vote 0 down vote accepted

Write a shell script which gets the files as parameters:


for filepath; do
  if [ "$parentpath" != "$filepath" ]; then # $file contains a /
  if [ -z "$parentpath" ]; then
    mkdir -p "$filename" && mv "$file" "$filename"
    mkdir -p "${parentpath}/$filename" &&
      mv "$filepath" "${parentpath}/$filename"

You can call this script as ./script *.ext1 *.ext2 *.ext3 for not too huge numbers of files or as find ... -exec ./script {} + for huge numbers.

share|improve this answer
Thank you very much! Works perfectly: exactly what I wanted. – paddymelon Jul 1 '13 at 2:52

Another Solution :

#!/usr/bin/env bash


for f in "$Dir"/*;
    mkdir -- "$SubDir"
    mv -- "${f}" "$SubDir/"
share|improve this answer

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.