I would like to know how to copy files with common names and paste them into another folder.

For example, I have folders f1, f2, f3 ... f50. Inside each folder, there are files named a#, b#, c#...z#. # is a kind of random number and they are different in f1, f2, f3 ... f50.

I would like to copy, for example, a files from all 50 f folders and paste them into a new folder.

Could you help me to do this?

  • are there other folders than the f1 f2 ... f50. and are there other files but the one you want in those folders? – Rob Sep 8 '16 at 18:36
  • 2
    reason I ask is that you can just do a cp f*/* newfolder and that will copy all the files from any folder that starts with the letter f into newfolder ;). – Rob Sep 8 '16 at 18:56
  • 1
    @Rob Not sure if this is useful, but cp f{1..50}/{a..z}* is a bit more precise. – wjandrea Sep 8 '16 at 19:17
  • 1
    @wjandrea Yeah that would work if there are other files, but a lot more typing if there are no other files ;) – Rob Sep 8 '16 at 19:29
  • Are there any duplicate filenames ? Like file a1 in folder f1 and f2 ? How would you want the command to deal with that ? – Sergiy Kolodyazhnyy Sep 10 '16 at 20:03

I assume you mean you have a structure something like:

├── f1
│   ├── a1
│   ├── a2
│   ├── b1
│   ├── b2
│   ├── c1
│   ├── c2
├── f2
│   ├── a3
│   ├── a4
│   ├── b3
│   ├── b4
│   ├── c3
│   ├── c4

and you want to end up with a directory like this:

├── a1
├── a2
├── a3
└── a4


  • the current working directory is the parent directory of all the directories f1 f2 f3

You could do:

mkdir a-files
for files in f*/a* ; do cp "$files" a-files ; done

to copy all files starting with a to a new directory a-files from all directories starting with f. You can repeat for files starting with b...

mkdir b-files
for files in f*/b* ; do cp "$files" b-files ; done

Note: if there are any duplicate filenames, each file written to the new directory will overwrite another with the same name, so at the end of the loop, the new directory would only have a copy of the last file to be written with that name. You could use the -n flag to cp to prevent overwriting, and then you would get the first file with that name instead of the last one:

for files in f*/a* ; do cp -n "$files" a-files ; done
  • This is exactly what I wanted. Thank you so much, Zanna! – Arnold Sep 11 '16 at 4:46
  • You're very welcome @Arnold :D – Zanna Sep 11 '16 at 4:59

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.