1

Following these two posts:

Move files to parent directory, prefixing file name with former subdirectory name

recursively add directory name to file name

I would like to do the same but with copying instead of moving. So simply, I have a directory containing subdirectories and subsubdirectories, where there are some files inside. I want to copy all the files to a another destination folder, but since some files have exact names, so I want to attach the name of the parent directories as a prefix to the filenames.

I am running on ubuntu 16.04

1 Answer 1

1

Given

$ tree folder1
folder1
├── folder2
│   ├── folder3
│   │   ├── name1.csv
│   │   ├── name2.csv
│   │   └── name3.csv
│   ├── name1.csv
│   ├── name2.csv
│   └── name3.csv
├── name1.csv
├── name2.csv
└── name3.csv

2 directories, 9 files

then you could do something like this to replace each path separator (/) in the original with _ for example:

$ find folder1 -type f -exec bash -c '
    for f; do echo cp -n "$f" path/to/newdir/"${f//\//_}"; done
' bash {} +
cp folder1/folder2/folder3/name2.csv path/to/newdir/folder1_folder2_folder3_name2.csv
cp folder1/folder2/folder3/name3.csv path/to/newdir/folder1_folder2_folder3_name3.csv
cp folder1/folder2/folder3/name1.csv path/to/newdir/folder1_folder2_folder3_name1.csv
cp folder1/folder2/name2.csv path/to/newdir/folder1_folder2_name2.csv
cp folder1/folder2/name3.csv path/to/newdir/folder1_folder2_name3.csv
cp folder1/folder2/name1.csv path/to/newdir/folder1_folder2_name1.csv
cp folder1/name2.csv path/to/newdir/folder1_name2.csv
cp folder1/name3.csv path/to/newdir/folder1_name3.csv
cp folder1/name1.csv path/to/newdir/folder1_name1.csv

Note that this doesn't guarantee unique namings if the original file or folder names already contain the _ character (which is why I included the -n no-clobber switch - just in case). You are of course free to choose a different (or no) delimiter.

Remove the echo once you are satisfied that it is doing the right thing.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .