简体   繁体   中英

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

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

You could do this at once with bash 's globstar option (that requires bash version 4.0 or newer), without using any external command:

shopt -s globstar
cp **/*.fq.gz "$destination"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM