Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 -i null myfile.txt returns

example two null, example four null, 

How can I return matched lines together with their line numbers like this:

  example two null, - Line number : 2   example four null, - Line number : 4   Total null count : 2 

I know -c returns total matched lines, but I don't how to format it properly to add total null count in front, and I don't know how to add the line numbers.

What can I do?

like image 891
London Avatar asked Oct 19 '10 12:10

London


People also ask

How do I show line numbers in grep?

To Display Line Numbers with grep MatchesAppend the -n operator to any grep command to show the line numbers. We will search for Phoenix in the current directory, show two lines before and after the matches along with their line numbers.

How do you grep and print the next N lines after the hit?

You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines.

How do you use grep to find lines ending with the pattern?

Matching the lines that end with a string : The $ regular expression pattern specifies the end of a line. This can be used in grep to match the lines which end with the given string or pattern. 11. -f file option Takes patterns from file, one per line.


2 Answers

-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 
like image 87
dogbane Avatar answered Sep 22 '22 10:09

dogbane


Use -n or --line-number.

Check out man grep for lots more options.

like image 44
Andy Lester Avatar answered Sep 22 '22 10:09

Andy Lester