Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

I've spent ages trying to build this and had a good look around for a way to do it. I have a directory tree which contains a set of folders and files. Some of the folders contain more than one file but most contain only a single one.

I'm trying to move all of the files which are on their own in directories one level below the root into the root. E.g:

  • Root is: /volume3
  • Single file in a sub folder: /volume3/20110103/20110103.log
  • File should end up as: /volume3/20110103.log

I know how to flatten the entire structure fairly easily but its the conditional part which I can't figure out how to do. Can anyone help?

share|improve this question
up vote 0 down vote accepted

You can accomplish that by using a small shell script.

#!/usr/bin/env bash
# go to "root" folder
cd /volume3
# loop over all items in "root" folder
for item in "$( ls )" ;
    # if it's a folder
    if [ -d "$item" ] ; then
        # and only contains a single item
        if [ "$( ls "$item" | wc -l )" = "1" ] ; then
            # move all files in the folder to the "root" folder
            mv "$item/"* .

(untested, but not a problem, since sane people always keep backups)

share|improve this answer
Add rm -r "$item" after the mv` line to remove the now empty directory. – Daniel Beck May 1 '11 at 22:48
Thanks, that works really well although I ran into trouble with the for loop, found I had to declare items=$(ls) followed by for item in items ; otherwise it never found anything. This works for me but I realise that if there were spaces in the folder names this wouldnt work! – Duncan May 2 '11 at 13:58

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.