We help IT Professionals succeed at work.

Grep: show filename and line number

R7AF
R7AF asked
on
I have 1GB directory which has many files with a string like 'abc123' in it. When I query the files now and pipe the results in a text file, I get a very big file back, which is probably the result of very long lines in the source file.

Now I use: grep -inR 'abc123' *, which returns filename, linenumber, plus the whole line, which can be very long. Is it possible to shorten that line, or even leave it out?
Comment
Watch Question

Most Valuable Expert 2013
Top Expert 2013

Commented:
-c, --count
      Suppress normal output; instead print a count of matching  lines
      for  each  input file.  With the -v, --invert-match option (see
      below), count non-matching lines.
wmp

Top Expert 2007

Commented:
can you give example of desired output? you last line is not clear

Commented:
Use awk to shorten the result.

eg . grep -inR 'abc123' * | awk { print $1 ,$2 }
Most Valuable Expert 2013
Top Expert 2013
Commented:
To show only filename and linenumber, you can do
grep -inR 'abc123' * |awk -F: '{print $1, $2}'
Top Expert 2007

Author

Commented:
Thanks!

But now I have another problem. This prints the count for each file. There are thousands of files with count=0, which I don't want to know about. Can these be left out of the results?

Commented:
use awk like this ...

awk '  if ($3 !=0) {print $1, $2 }
Most Valuable Expert 2013
Top Expert 2013
Commented:
Strange! Why should grep display files with 0 matching lines?
Anyway -
grep -inR 'abc123' * |awk -F: '$2!=0  {print $1, $2}'
Most Valuable Expert 2013
Top Expert 2013

Commented:
... or, with my first suggestion
grep -ciR 'abc123' * |awk -F: '$2!=0  {print}'
This will not display line numbers, however, only the count of matching lines (>0)!
 
Top Expert 2007

Author

Commented:
Thanks for all suggestions. Both these commands do what I need. It turns out that about 20 files have matching results. Because all files have only one match, the first command is more usefull in this case. I will split the points.

grep -inR 'abc123' * |awk -F: '{print $1, $2}'
grep -ciR 'abc123' * |awk -F: '$2!=0  {print}'