98
votes

I am trying to search my rails directory using grep. I am looking for a specific word and I want to grep to print out the file name and line number.

Is there a grep flag that will do this for me? I have been trying to use a combination of -n and -l but these are either printing out the file names with no numbers or just dumping out a lot of text to the terminal which can't be easily read.

ex:

  grep -ln "search" *

Do I need to pipe it to awk?

5

5 Answers

156
votes

I think -l is too restrictive as it suppresses the output of -n. I would suggest -H (--with-filename): Print the filename for each match.

grep -Hn "search" *

If that gives too much output, try -o to only print the part that matches.

grep -nHo "search" * 
32
votes
grep -rin searchstring * | cut -d: -f1-2

This would say, search recursively (for the string searchstring in this example), ignoring case, and display line numbers. The output from that grep will look something like:

/path/to/result/file.name:100: Line in file where 'searchstring' is found.

Next we pipe that result to the cut command using colon : as our field delimiter and displaying fields 1 through 2.

When I don't need the line numbers I often use -f1 (just the filename and path), and then pipe the output to uniq, so that I only see each filename once:

grep -ir searchstring * | cut -d: -f1 | uniq
20
votes

I like using:

grep -niro 'searchstring' <path>

But that's just because I always forget the other ways and I can't forget Robert de grep - niro for some reason :)

3
votes

The comment from @ToreAurstad can be spelled grep -Horn 'search' ./, which is easier to remember.

grep -HEroine 'search' ./ could also work ;)

For the curious:

$ grep --help | grep -Ee '-[HEroine],'
  -E, --extended-regexp     PATTERNS are extended regular expressions
  -e, --regexp=PATTERNS     use PATTERNS for matching
  -i, --ignore-case         ignore case distinctions
  -n, --line-number         print line number with output lines
  -H, --with-filename       print file name with output lines
  -o, --only-matching       show only nonempty parts of lines that match
  -r, --recursive           like --directories=recurse
0
votes

Here's how I used the upvoted answer to search a tree to find the fortran files containing a string:

find . -name "*.f" -exec grep -nHo the_string {} \;

Without the nHo, you learn only that some file, somewhere, matches the string.