Skip to content

Learning Perl Challenge: Remove intermediate directories

I often run into situations where I have directories that contain only one file, a subdirectory, which contains 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:

A Finder window showing the nested directories A, B, C, D, and E, with five text files in E
Before: A/B/C/D/E in a direct line

and turn it into this one, with a single directory with the files that were at the end:

A Finder window showing the same five text files directly in A, with no directories between them
After: the files from E are in A

However, you should only move 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:

A Finder window showing the nested directories A, B, C, D, and E, with five text files in E, and a directory F next to D
Before: A/B/C has two branches, D and F

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

A Finder window showing the five text files in D, with E gone and the directory F, highlighted, still next to D
After: the files from E move up only into D