david
david

Reputation: 825

Search filenames for a list of patterns and copy to destination

I have a list of patterns in filenames.txt, and I want to search a folder for filenames containing the names.

patterns.txt:

254b    
0284ee    
001ty    
288qa

I want to search a folder for filenames containing any of these patterns in its filename and copy all found files to a destination directory.

So far i found a solution to view files as follows:

set -f; find ./ -type f \( $(printf -- ' -o - iname *%s*' $(cat patterns.txt) | cut -b4-) \); set +f

I can find all files based on the patterns on my patterns.txt file, but how do I copy them top a newfolder ?

Upvotes: 0

Views: 206

Answers (1)

dash-o
dash-o

Reputation: 14491

Assuming target folder will not need to maintain the original hierarchy (or that the input directory does not have sub directories), using find, grep, and xargs should work:

find . -type f -print0 |
  grep -z -i -F -f patterns.txt |
  xargs -0 -s1000 cp -t /new/folder

The sequence has the advantage of bulking the copy - will be efficient for large number of files. Using NUL to separate file name should allow any special character in the file name.

Upvotes: 1

Related Questions