简体   繁体   中英

Bash find line number

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

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

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.)

To get only the line numbers, you could use

grep -n 'regex' | sed 's/^\([0-9]\+\):.*$/\1/'

Or you could simply use sed:

sed -n '/regex/=' file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM