Search code examples
linuxbashshellgrepcut

Bash grep output filename and line no without matches


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.


Solution

  • 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