Question

I need to get a list of matches with grep including filename and line number but without the match string

I know that grep -Hl will give only file names and grep -Hno will give filename with only matching string. But those not ideal for me. I need to get a list without match but with line no. For this grep -Hln doesn't work. I tried with grep -Hn 'pattern' | cut -d " " -f 1 But it doesn't cut the filename and line no properly.

Was it helpful?

Solution 2

You were pointing it well with cut, only that you need the : field separator. Also, I think you need the first and second group. Hence, use:

grep -Hn 'pattern' files* | cut -d: -f1,2

Sample

$ grep -Hn a a*
a:3:are
a:10:bar
a:11:that
a23:1:hiya

$ grep -Hn a a* | cut -d: -f1,2
a:3
a:10
a:11
a23:1

OTHER TIPS

awk can do that in single command:

awk '/pattern/ {print FILENAME ":" NR}' *.txt

I guess you want this, just line numbers:

grep -nh PATTERN /path/to/file | cut -d: -f1

example output:

12
23
234
...

Unfortunately you'll need to use cut here. There is no way to do it with pure grep.

Try

grep -RHn Studio 'pattern' | awk -F: '{print $1 , ":",  $2}'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top