Search code examples
linuxunixgrepcygwin

Cygwin/Linux - Find files which contain strings from a file


I am trying to find files which contain strings located in a text file within their file names and then copy these files to a new directory.

Example 1.txt contains strings line by line:
1234
1666

Directory contains files:
JOHN-1234-TEXT.CSV
DAVE-1666-TEXT.CSV
LAURA-1826-TEXT.CSV

If code is successful it will copy the files to a new specified directory:
JOHN-1234-TEXT.CSV
DAVE-1666-TEXT.CSV

If anyone can i help i would greatly appreciate it.


Solution

  • find + grep + tr + xargs pipeline approach:

    find olddir -type f -print | grep -f "1.txt" | tr '\n' '\0' | xargs -0 -I{} cp {} newdir
    

    olddir directory contains the initial files

    grep -f "1.txt" - obtains patterns from file, one per line