0

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 ?

jww
  • 97,681
  • 90
  • 411
  • 885
david
  • 805
  • 1
  • 9
  • 21
  • Have you tried piping the result to xargs? "| xargs -I {files} cp {files} /path/to/new/folder" – folq Dec 06 '19 at 11:45
  • Do you need to handle files in sub directories. If YES, do you want all files copied to a `flat` destination, or do you have to maintain the hierarchy? (that is if there is ./a/b/c.txt, should it be (1) target/c.txt, or (2) target/a/b/c.txt – dash-o Dec 06 '19 at 12:56

1 Answers1

1

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.

dash-o
  • 13,723
  • 1
  • 10
  • 37