linuxbashubuntuunixfile-globs

Get file globs from a file and find these files


I have a file called "file.txt" and it contains globs. Contents:

*.tex
*.pdf
*C*.png

I need to get these extensions from the file and then find the files containging these globs in the current directory (preferably using find, anything else is fine too).

I used

grep "" file.txt | xargs find . -name 

but I get this error:

find: paths must precede expression: `*.pdf'

Using Ubuntu


Solution

  • The original code needs the -n 1 argument to be passed to xargs, to pass only one glob to each copy of find, as each glob expression needs to be preceded with a -name (and attached to any other -name expressions with -o, the "or" operator).

    More efficient is to run find just once, after constructing an expression that puts all your -name operators on a single command line, separated with -os.

    #!/usr/bin/env bash
    #              ^^^^- MUST be run with bash, not /bin/sh
    
    find_expr=( -false )
    while IFS= read -r line; do
      find_expr+=( -o -name "$line" )
    done <file.txt
    
    find . '(' "${find_expr[@]}" ')' -print