开发者

How do I grep the contents of files returned by grep?

When I look for log files with an error message using grep error *log, it returns a list of logfiles

$grep error *log

Binary file out0080-2011.01.07-12.38.log matches
Binary file out0081-2011.01.07-12.38.log matches
Binary file out0082-2011.01.07-12.38.log matches
Binary file out0083-2011.01.07-12.38.log matches

However, these are text, not binary files.

I am not sure why these are considered binary, the first few lines contain the following non-error messages:

out0134
-catch_rsh /opt/gridengine/default/spool/compute-0-17/active_jobs/327708.1/pe_hostfile
compute-0-17

I would like to grep the contents of the returned files for an error message and return the names of the files with the messag开发者_如何学JAVAe.

How can I grep the contents of the returned files, rather than this list of returned files, as happens with grep error *log | grep foo?


Here's the answer you might be looking for:

grep -l foo $(grep -l error *.log)

-l tells grep to print filenames only; that does the first grep, then substitutes the result into the next grep's command. Alternatively, if you like xargs:

grep -l error *.log | xargs grep -l foo

which does the same thing, using xargs to call the second grep with the first grep's results as arguments.


-a, --text
Process a binary file as if it were text; this is equivalent to the --binary-files=text option.

grep -a "some error message" *.log

Btw, here is how grep determines binary from text files

If the first few bytes of a file indicate that the file contains binary data, assume that the file is of type TYPE. By default, TYPE is binary...

Update

If you want just a list of file names which contain the word foo within the line that also contains error then you can do one or the other of these:

grep -la "error.*foo" *.log <-- assumes foo comes after error


I do this.

$find . -type f -name *.log | fgrep -v [anything unwanted] | xargs grep -i [search inside files]


A comment asked about how to only grep for foo in the files that match the error, you can:

for i in *log ; do
    grep -a error $i >/dev/null 2>&1 && {
        echo -e "File $i:\n\t"
        grep -a foo $i
    }
done
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜