Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show filename and line number in grep output

Tags:

grep

awk

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?

like image 467
trev9065 Avatar asked Nov 12 '11 16:11

trev9065


People also ask

How do I grep and show line numbers?

To Display Line Numbers with grep MatchesAppend the -n operator to any grep command to show the line numbers. We will search for Phoenix in the current directory, show two lines before and after the matches along with their line numbers.

How do I print a grep filename?

grep -n 'string' filename : Force grep to add prefix each line of output with the line number within its input file. grep --with-filename 'word' file OR grep -H 'bar' file1 file2 file3 : Print the file name for each match.

How do I grep a line number from a file?

The -n ( or --line-number ) option tells grep to show the line number of the lines containing a string that matches a pattern. When this option is used, grep prints the matches to standard output prefixed with the line number.


Video Answer


1 Answers

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" *  
like image 138
spokeadoke Avatar answered Sep 30 '22 20:09

spokeadoke