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

后端 未结 8 417
忘掉有多难
忘掉有多难 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条回答
  •  梦毁少年i
    2021-01-29 17:58

    grep find the lines and output the line numbers, but does not let you "program" other things. If you want to include arbitrary text and do other "programming", you can use awk,

    $ awk '/null/{c++;print $0," - Line number: "NR}END{print "Total null count: "c}' file
    example two null,  - Line number: 2
    example four null,  - Line number: 4
    Total null count: 2
    

    Or only using the shell(bash/ksh)

    c=0
    while read -r line
    do
      case "$line" in
       *null* )  (
        ((c++))
        echo "$line - Line number $c"
        ;;
      esac
    done < "file"
    echo "total count: $c"
    

提交回复
热议问题