0

I need to copy some files that are like this:

folder1/name1.csv
folder1/name2.csv
folder2/name1.csv
folder2/name2.csv
folder3/name1.csv
folder3/name2.csv

All folder* are subdirectory of a directory. What I want to do is to copy all the file "name*" into a new directory new_dir but I have to change their name. Looking for help I tried

find . -name 'name*.csv' -exec cp --backup=t '{}' new_dir/ \;

But I obtain "cp: './new_dir/name1.csv' e './new_dir/name1.csv' are the same file".

How can I add a prefix or suffix to the name so that I can copy them? Adding an integer is ok, so that in the new_dir files will be as:

new_dir/name10.csv
new_dir/name21.csv
new_dir/name12.csv
new_dir/name23.csv
new_dir/name14.csv
new_dir/name25.csv
...

Or, even better, if I can rename the file adding the name of the folder from where they are copied, as:

new_dir/name1folder1.csv
new_dir/name2folder1.csv
new_dir/name1folder2.csv
new_dir/name2folder2.csv
new_dir/name1folder3.csv
new_dir/name2folder3.csv
...

Thanks in andvance.

1 Answer 1

0

Given

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

0 directories, 9 files

then using a shell loop with parameter expansion to slice'n'dice the names

$ for f in folder*/name*.csv; do 
    b="${f##*/}"; 
    echo cp "$f" new_dir/"${b%.csv}${f%/*}.csv"
  done
cp folder1/name1.csv new_dir/name1folder1.csv
cp folder1/name2.csv new_dir/name2folder1.csv
cp folder1/name3.csv new_dir/name3folder1.csv
cp folder2/name1.csv new_dir/name1folder2.csv
cp folder2/name2.csv new_dir/name2folder2.csv
cp folder2/name3.csv new_dir/name3folder2.csv
cp folder3/name1.csv new_dir/name1folder3.csv
cp folder3/name2.csv new_dir/name2folder3.csv
cp folder3/name3.csv new_dir/name3folder3.csv

You must log in to answer this question.

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