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

后端 未结 8 419
忘掉有多难
忘掉有多难 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 17:46

    Just thought I'd something that might help you in the future. To search multiple string and output line numbers and browse thru the output, type:

    egrep -ne 'null|three'

    will show:

    2:example two null,  
    3:example three,  
    4:example four null,   
    

    egrep -ne 'null|three' | less

    will display output in a less session

    HTH Jun

    0 讨论(0)
  • 2021-01-29 17:50

    use grep -n -i null myfile.txt to output the line number in front of each match.

    I dont think grep has a switch to print the count of total lines matched, but you can just pipe grep's output into wc to accomplish that:

    grep -n -i null myfile.txt | wc -l
    
    0 讨论(0)
  • 2021-01-29 17:55

    or in perl (for completeness...):

    perl -npe 'chomp; /null/ and print "$_ - Line number : $.\n" and $i++;$_="";END{print "Total null count : $i\n"}'
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-29 18:04

    Or use awk instead:

    awk '/null/ { counter++; printf("%s%s%i\n",$0, " - Line number: ", NR)} END {print "Total null count: " counter}' file
    
    0 讨论(0)
提交回复
热议问题