2

I need to do a search on a number of files in a file system to look for a string "RUSH2112". I have completed the following command however I am not sure if this is correct. I stand in the mounted file system.

find . -type f -exec grep -i1 "Rush2112" {} \; 
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Deirdre
  • 121

1 Answers1

6

To look for a string (not a regular expression) without caring for case, use grep -iF STRING (where STRING should be the quoted string you are looking for).

To recurse over all regular files in a directory hierarchy, do

find . -type f -exec grep -iF STRING /dev/null {} +

The main difference between this and your command is that this will execute grep for groups of found files. Your command would run grep once for each found file which may be slower if there are many files. It's the + at the end that makes this difference.

The other difference is that since grep is invoked with more than one file, its output will contain the pathnames of the files where matches are found. The /dev/null is there to force this behaviour in case grep happens to be invoked with only a single file. You may use grep's -H option instead of including /dev/null if your implementation of grep has that non-standard (but common) option.

Some implementation of grep also has the option to recurse directories by itself, without the help of find. This is often done with an -R option:

grep -R -iF STRING .

Note that GNU grep also has a -r option that is slightly different from its -R option (with -r, symbolic links will not be followed, which would more closely mimic the behaviour you'd get with running grep via find . -type f).


If what you're after is to find only the pathnames of the files that contain the string and not necessarily the actual lines from those files that match, then you may do that in a number of different ways (all largely analogous to what's mentioned above).

  • Use grep -q as a test on each file:

    find . -type f -exec grep -qiF STRING {} ';' -print
    
  • Use grep -l across groups of files found by find:

    find . -type f -exec grep -ilF STRING {} +
    
  • Use recursive grep -l:

    grep -R -ilF STRING .
    

If you are wanting to do further processing of the files that contain the given string, then I would go with the first of these alternatives:

find . -type f -exec grep -qiF STRING {} ';' -exec sh -c '
    for pathname do
        # Process "$pathname" here
    done' sh {} +

or, doing the grep inside the in-line script:

find . -type f -exec sh -c '
    for pathname do
        if grep -qiF STRING "$pathname"; then
            # Process "$pathname" here
        fi
    done' sh {} +

Related:

Kusalananda
  • 333,661