Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

1 Answer

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 )" ;
do
    # 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/"* .
        fi
    fi
done

(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
add comment

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.