20

The following grep

grep -r -e -n coll *

will display

fullpath/filename:  <tag-name>coll</tag-name>

I would like to know what line has the following text, I tried adding -n, but it did not work. I tried adding | grep -n *, but it did something weird.

What I would like to see (I don't care about format) is

fullpath/filename:10:  <tag-name>coll</tag-name>
  • 1
    I see line numbers when using the -n option. Can you post the output of what you get? – Kris Harper Nov 8 '11 at 15:58
19

You should put -e at the end of the options list: grep -rne coll *

| improve this answer | |
17

no need for -r & -e !

get line number of a pattern!

grep -n "pattern" file.txt

if you want to get only the line number as output add another grep command to it !

grep -n "pattern" file.txt | grep -Eo '^[^:]+'
| improve this answer | |
  • 2
    To get just the line number, it's easier to use cut, e.g. cut -f1 -d: – wjandrea Jul 27 '18 at 16:21
2

To grep a pattern in a specific file, and get the matching lines:

grep -n <Pattern> <File> | awk -F: '{ print $1 }' | sort -u

or using cut as suggested by @wjandrea:

grep -n <Pattern> <File> | cut -f1 -d: | sort -u

where

  • <Pattern> is a quoted glob pattern (use option -E for regexp);
  • <File> is the file you are interested in;
  • the first pipe awk ... filters the line numbers in the output of grep (before : on each line);
  • the second pipe ensures that line numbers only appear once.
| improve this answer | |
  • To get just the line number, it's easier to use cut than Awk, e.g. cut -f1 -d: – wjandrea Jul 27 '18 at 16:22
  • @wjandrea Easier in what way? – Jonathan H Jul 27 '18 at 22:38
  • I mean the syntax is simpler – wjandrea Jul 27 '18 at 22:39
  • @wjandrea That sounds very objective. – Jonathan H Jul 27 '18 at 22:43
  • @wjandrea Sorry for the sarcasm, I edited to include your suggestion :) – Jonathan H Jul 27 '18 at 22:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.