Question

I have a directory with several thousand subdirectories inside (no subdirectories within those subdirectories however), and I need to flatten the contents of only some of the subdirectories, so basically bringing the contents of those directories to the root directory.

But I can't do that with all the subdirectories, and the ones which I can't flatten have multiple files in them.

Any way to do this automatically? Python script, perl script, bash, or whatever? I really, really, really don't want to have to do this by hand...

Was it helpful?

Solution

Something like this, in bash (foo represents the directory you want to flatten):

for x in foo/*
do
    COUNT=`ls -1 "$x" | wc -l`

    if ([ -d "$x" ] && (test $COUNT -le 1))
    then
        if test $COUNT -eq 1; then
            mv "$x"/* $1
        fi
        rmdir "$x"
    fi
done

This will also remove an empty subdirectory from foo.

You can also put this into a shell script file and use $1 as the directory name:

# Exit it a directory name isn't given

if [ "$1" = "" ] ; then
    echo "Usage: $0 directory"
    echo "Flattens directory"
    exit
fi

for x in "$1"/*
do
    COUNT=`ls -1 "$x" | wc -l`

    if ([ -d "$x" ] && (test $COUNT -le 1))
    then
        if test $COUNT -eq 1; then
            mv "$x"/* "$1"
        fi
        rmdir "$x"
    fi
done

You can put that into a file called flatten then run sh flatten foo to flatten the directory foo. Or, chmod +x flatten and run ./flatten foo. Ultimately, if you use it a lot over time, you can move it to a directory that's in our PATH so you can just type flatten foo. What I have is a bin file in my home directory on Linux where I put my own tools I want when I'm logged in, and I put my ~/bin in my PATH (set in the bash profile).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top