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?
or in perl (for completeness...):
-n
returns line number.-i
is for ignore-case. Only to be used if case matching is not necessaryCombine with
awk
to print out the line number after the match:Use command substitution to print out the total null count:
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:
Or use
awk
instead: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,Or only using the shell(bash/ksh)
Use
-n
or--line-number
.Check out
man grep
for lots more options.