Copy files with specific naming patterns from Linux shell

TL, DR

Sometimes you may need to copy a large number of files, and your file explorer/file search will be painfully slow. If you use Linux, you can easily copy files with a specific naming pattern using only the shell, saving time and effort.

Need to copy many files?

Sometimes we need to copy a large number of files. The pain may already start with displaying all files in a file explorer, or awaiting a file search for a certain naming patter to return hundreds – or thousands – results.

Luckily, there is a powerful tool at hand, provided you are a Linux user. Your shell. Let’s have a look to the copy of the cp command:

cp [options] [source…] [destination…]

Now, I need to say that there are about a zillion way to achieve the same result – copy files with a certain pattern in their name. You could use find a pipe the output in a cp command, or ls and grep, or rsync, or…it may be an endless list.

Some of the approaches may provide better performance than others, and it may also depend on your specific use case/setting. Here I’ll simply present what worked better for me in terms of performance and simplicity.

My use case was that I had to copy a large number of files with different prefixes to another folder. Those files all had separate suffixes (in that case, the data when every file was generated).

The command I used (and still use happily to date) is:

cp -- {pref1,pref2,pref3}* /destfolder/

Command breakdown

Let’s break down the various parts of the command:
cp: is the main copy command in the Linux shell.
--: it is needed in case one of your prefixes starts with a - or a --. Else the shell may mistake it for an option (and probably fail miserably).
{ }: whatever it is between the curly brackets is treated as alternative for the shell command.
pref1, pref2, pref3: a comma separated list of prefixes in the file names you want to copy. You can put more or less items, as you need.
*: means that the second part of the file name after the prefix can be whatever.
/destfolder/: is the path to your destination folder.

In summary, we showed how to copy many files with specific naming patterns in one go using the Linux shell and cp command. Hope you can find this useful for your projects!

Related links

  • Linux shell cp manpage link

Do you like our content? Check more of our posts in our blog!