Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash find line number

Tags:

linux

bash

I have this script:

find . -name "$2" -print | xargs grep --colour=auto "$1"

It searches for a $1 word in $2 matching files. How can I make it print the line number on which the word has been found.

Thanks

like image 302
yonutix Avatar asked Dec 15 '22 12:12

yonutix


2 Answers

You don't need to use find and xargs here. You can use recursive grep like this:

grep -RHn --colour=auto "$1" --include='$2' .

Options:

-n  # for printing line numbers
-R  # for recursive grep
-H  # for printing file names
like image 88
anubhava Avatar answered Dec 26 '22 20:12

anubhava


From man grep:

-n, --line-number
     Prefix each line of output with the 1-based line number within its input file.  (-n is specified by POSIX.)
like image 32
m0skit0 Avatar answered Dec 26 '22 18:12

m0skit0