Efficient way to grep

Hi Experts,

I've been trying simple grep to search for a string in a huge number of files in a directory.

grep <pattern> *

this gives the search results as well as the following -

grep: <filename>: Permission denied
grep: <filename>: Permission denied

for files which I don't have read permissions on.

I have three questions-
1) is there any way to eliminate these messages ?
2) is there any way to search in those files as well ?
3) is there any different approach to search for a string in a heap of files ( apart from sed)

To dump the errors

% grep <pattern> * 2>/dev/null
  1. you can redirect STDERR to /dev/null thus
    text grep string files 2>/dev/null
  2. If you have an account with the right to read them, issue the command from that account
  3. grep is about the fastest string search available, however your approach will eventually result in a "Too many arguments" failure, you should try grep -r or using a command to isolate the files you need to search, eg.
    text find ./ -type f -name *.pl | xargs grep 'use strict' 2>/dev/null

Try this, it will check only the files having permissions and we can also avoid the errors.

find . -type f -perm 666 -exec grep "pattern" {} \;

Change the permission, as what ever you want.

2 Likes

Another way.

# First eliminate errors from directories which you cannot read
# Then check that you can read each file before using grep
find . -type f -print 2>/dev/null | while read FILENAME
do
     if [ -r "${FILENAME}" ]
     then
            grep "string" "${FILENAME}"
     fi
done