3

Possible Duplicate:
Use grep to report back only line numbers

I only want to see the line number. I don't need to see the remaining output.

Community
  • 1
  • 1
choujayyl
  • 91
  • 1
  • 4
  • 12

3 Answers3

5

Pipe your grep -n output, which normally looks something like:

11: stuff that matched
43: more stuff that matched

through sed to strip out the matching parts:

grep -n pattern file | sed -e 's/:.*//g'

11
43
Amir T
  • 2,708
  • 18
  • 21
  • Wonderful,thank you,though I have anther question:how can i get the first match result? – choujayyl Dec 24 '12 at 09:59
  • And can you introduce the string " :.* ",what are they representative? – choujayyl Dec 24 '12 at 10:14
  • its a substitution of the colon and anything that appears after it with the empty string "//" there is an explanation of the regular expression here where you can also play around with it: http://regex101.com/r/nS9jM7 – Amir T Dec 24 '12 at 21:53
  • Ok,but you don't anwser me the anther question:how can i get the first match result? – choujayyl Dec 25 '12 at 00:57
  • If you want to get the first line (of anything) you can pipe it to "head -n1" so "grep -n pattern file | sed -e 's/:.*//g' | head -n1 – Amir T Dec 26 '12 at 22:38
0

grep -n or --line-number option will do this for you. You can find this information in the grep help file, which you can find by using grep --help or grep --help | less to read it more carefully. Also consider using the manual page: man grep

L0j1k
  • 12,255
  • 7
  • 53
  • 65
0

You could use awk too.

grep -n word file | awk -F: '{ print $1 }'

As @Barmar pointed out you could just use an awk one-liner as such:

awk '/regex/ { print NR }' file

Since you don't have awk you could also use cut:

grep -n word file | cut -d: -f1
squiguy
  • 32,370
  • 6
  • 56
  • 63