I often run into situations where I have directories that contain only one file, a subdirectory, with contain only one file, a subdirectory, and so on for a long chain, until I get to the interesting files. These situations come up when I have only part of a data set so the files that would be in other directories aren’t there, and I find it annoying to deal with these long directory specifications. So, this challenge is to fix that by collapsing those one-entry directories into a single one.
For example, you should take this structure, where you have A/B/C/D/E in a direct line with no other branches:
and turn it into this one, with a single directory with the files that were at the end:
However, you should only moves files up if the directory above it has only one entry (which must be a subdirectory!). In this example, A/B/C has two subdirectories in it:
so the the files in E should only move up into D. Otherwise, the files from the two branches in C would get mixed up with each other.
In the second example, shouldn’t D and F end up in A, since B contains *only* C?
I hadn’t thought about that. I’ll let you decide!
Not as easy as it seems. My solution works as Szymon proposed. Some details would still need discussion with the client, though 🙂 For example, each empty directory without siblings disappears. The script probably does not work correctly for /, but I did not have enough courage to test it. Also, I might have used a bit more than Learning Perl teaches – I have read more books.
I’m mainly a C++ programmer, but I tried my hand at perl this time. I used a recursive function and shell commands.