Ubuntu – How to copy files with common names and paste them into another folder

bashcommand linefiles

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?

Best Answer

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:

a-files
├── a1
├── a2
├── a3
└── a4

Assuming:

  • 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