Search code examples
bashcopypaste

Copy paste files with certain extension from several subfolders in bash


Sorry for being naive, but I struggle for long time.

I have a directory that looks like this

dir 
 |--folder1
 |     |--- subfolder1
 |     |--- ...
 |     |--- subfolder100
 |
 |--folder2 
      |--- subfolder1
      |--- ...
      |--- subfolder100

Each folder and subfolder contains among others files with the extension ".fq.gz"

I want to list all these files, and then copy them to my destination folder

destination=/path/to/folder/

I have tried this but it does not work for me and I have no idea why

ls -R | grep "\.fq.gz" | xargs -I {} cp {} "$destination"

the error is no such file in the directory


Solution

  • The best way to explain what goes wrong is to look what is actually fed into the xargs. So,

    ls -R | grep "\.fq.gz"
    

    This will give you a list of files without their path, so

    file1.fq.gz
    file2.fq.gz
    ...
    

    and not

    folder1/subfolder3/file1.fq.gz
    folder2/subfolder7/file2.fq.gz
    ...
    

    And that is why it doesn't work.

    THE tool for this kind of actions is of course find, as in

    find dir -name '*.fq.gz' -exec cp {} "$destination" \; -print