0

Whats a good way of “collapsing“ subfolders of a specified directory into a single folders whose name is a join the subfolders?

So given this directory structure…

./zero.csv
./reports/r1/a/b/c/one.csv
./reports/r2/a/two.csv
./reports/r3/x/y/z/three.csv
./reports/r4/x/y/four.csv

How could I specify subfolders of./reports should collapse - resulting in:

./zero.csv
./reports/r1.a.b.c/one.csv
./reports/r2.a/two.csv
./reports/r3.x.y.z/three.csv
./reports/r4.x.y/four.csv

Thanks

1 Answers1

1

Mass-rename using prename aka perl-rename:

shopt -s globstar
prename -n 's{ (reports)/(.+)/ }{ "$1/" . $2=~s{/}{.}gr . "/" }xe' reports/**/*.csv

(Change -n to -v when the output looks right.)

Clean up leftover empty directories:

find reports -depth -type d -exec rmdir -v --ignore-fail-on-non-empty {} \;

prename applies Perl expressions (often s/regex/replacement/ but not limited to) to each specified path. Here it uses s{regex}{replacement} to avoid slash-related headaches, matching paths against (reports)/(.+)/. With the x flag, the replacement itself is another Perl expression that keeps the 1st group (reports) but replaces slashes with periods in the 2nd group (.+).

grawity
  • 501,077