0

I am trying to copy multiple files with different names from different directories, to one same new directory. The names of the directories are the same as the beginning of each filename. For example from directory /mnt/data/files/xyz, I want to copy file xyz_5 to directory /mnt/data/myname/new. From directory /mnt/data/files/abc, I want to copy file abc_7 to directory /mnt/data/myname/new.

I have 60 files I need to do this for. What I do now:

cd /mnt/data/files/xyz;
cp -v *_5 /mnt/data/myname/new

I do this for each file. But can I do this with a single piece of code?

  • The cp file target command behaves differently depending on the target. a) target not present: create target as copy of file, b) target present and a file: (try to) overwrite target with file c) target present and a directory: copy file into directory target. For multiple files it is simply cp file1 file2 .... target which will copy all specified files into target directory. If target is not a directory it will produce an error and abort. – Fiximan Sep 3 '15 at 12:16
  • 1
    Please edit your question and clarify what you need. Do you only need to copy one file from each directory? All files that start with the given prefix? Does each prefix directory (abc/, xyz/, etc.) only have a single file? Do you want to copy files from every directory in /mnt/data/files/ or from only some of them? Which ones? The more specific your question is, the more likely it is that we can provide an answer that will help you. – terdon Sep 3 '15 at 12:39
1

The question is not very clear, but probably you just want to do

cp -v /mnt/data/files/xyz/*_5 /mnt/data/files/abc/*_7 /mnt/data/myname/new/
1

A simple for loop can do the job:

for i in /mnt/data/files/*; do
  [ -d "$i" ] && cp -v "${i}/${i}_5" /mnt/data/myname/new/
done

The for loop runs trough the content of the directory /mnt/data/files/. Inside the loop [ -d "$i" ] checks if the item is a directory. If yes, copy the file in this directory with the same same name as the directory and ending with _5 to the target directory /mnt/data/myname/new/.

  • Thank you, but as I need different file names, so not all ending in _5 (some in _7, some in _9, some in _8), this will not work. – SSK Sep 3 '15 at 12:49
  • 1
    @SSK what do you mean by "some", is there a rule? If not just use ${i}/${i}_* instead. – chaos Sep 3 '15 at 14:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.