Home > Enterprise >  Gluing together files in multiple, nested subdirectories in bash
Gluing together files in multiple, nested subdirectories in bash

Time:07-21

I have a set of directories that looks like this:

www.me.com/a/b/c/file.csv
www.you.com/a/b/c/d/e/file.csv
www.us.com/a/file.csv

In bash, I'm attempting to rename the file with the directory path:

www.me.com/a/b/c/www.me.comabcfile.csv
www.you.com/a/b/c/d/e/www.you.comabcdefile.csv
www.us.com/a/www.us.comafile.csv

The sequence I've tried is:

rename 's/(.*)\//$1\/$1/' *

This does not have the desired outcome, instead creating monstrously large file names.

What am I doing wrong?

CodePudding user response:

Since the job doesn't seem performance-relevant, we can take our time and do it in a loop for better readability:

#!/bin/bash

FN="file.csv"

while read FP; do
  test -f "$FP" || continue
  D=$(dirname "$FP")
  NN=$(echo "$D" | sed 's#^\.##; s#/##g')"$FN"
  mv -v "$FP" "$D/$NN"
done < <(find . -name "$FN")
  • Related