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).