How can I format my grep output to show line numbers at the end of the line, and also the hit count?

后端 未结 8 606
忘掉有多难
忘掉有多难 2021-01-29 17:46

I\'m using grep to match string in a file. Here is an example file:

example one,
example two null,
example three,
example four null,

grep

8条回答
  •  独厮守ぢ
    2021-01-29 18:02

    -n returns line number.

    -i is for ignore-case. Only to be used if case matching is not necessary

    $ grep -in null myfile.txt
    
    2:example two null,
    4:example four null,
    

    Combine with awk to print out the line number after the match:

    $ grep -in null myfile.txt | awk -F: '{print $2" - Line number : "$1}'
    
    example two null, - Line number : 2
    example four null, - Line number : 4
    

    Use command substitution to print out the total null count:

    $ echo "Total null count :" $(grep -ic null myfile.txt)
    
    Total null count : 2
    

提交回复
热议问题