0

I want to copy several files from one directory to another, with different extensions

So I would write something like:

cp -r dir1/*.gif dir2

But I also want to copy all .jpg files in the same command. Is there some sort of AND command that would work?

  • Small wording detail: If you want jpg matches AND gif matches, this is technically an OR expression, because you want to match either pattern1 OR pattern2. – Philippos Jun 11 at 8:02
2

You can simply list them all:

cp dir1/*.gif dir1/*.jpg dir2

The way this works is that the shell expands out the * parameters and passes all the matching names to cp so it might actually run

cp dir1/file1.gif dir1/file2.gif dir1/file3.jpg dir1/file4.jpg dir2
2
cp /path/src/*.{gif,jpg} /path/dest 

Info about wildcards and globbing patterns.

In particular:

{ } (curly brackets)
terms are separated by commas and each term must be the name of something or a wildcard. This wildcard will copy anything that matches either wildcard(s), or exact name(s) (an “or” relationship, one or the other).

For example, this would be valid:

cp {*.doc,*.pdf} ~
This will copy anything ending with .doc or .pdf to the users home directory. Note that spaces are not allowed after the commas (or anywhere else).
  • Better cite the explanation for {,} instead of trusting on external links – Philippos Jun 11 at 8:00
0

For loops are nice for this kind of thing.

Example: Copy all .py and .ipynb files from the current directory to a directory called dst/

for file in *.py *.ipynb; do cp $file /dst/; done
  • Could you explain what benefit there is to using a loop instead of cp -- *.py *.ipynb /dst/? – Stephen Kitt Jun 11 at 9:07
  • A for loop is more versatile in that you can use any command, as well as chain several commands together. Other than for copying/renaming files, I also use this pattern often when I'm doing text replacement with sed. The possibilities are limitless. – Clayton Mork Jun 12 at 13:40
  • I didn’t mean for you to explain it (to me) in a comment; please edit your answer to improve the explanation. And while the possibilities are limitless, we tend to prefer answers within the scope of the question (which is about cp in particular here, so ideally you’d explain why a for loop is better specifically with cp). – Stephen Kitt Jun 12 at 13:50

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.