When using the grep command, to format the output such that each matching line shows the line number and match count (i.e., the occurrence count of the match on that line) at the end, you can use the -n option of grep to display line numbers and combine it with awk for calculating and displaying the match counts.
Example Demonstration
Assume we have a file named example.txt with the following content:
shellhello world hello hello world world world hello goodbye world
We want to find all lines containing the word world and display the line number and the occurrence count of world on that line at the end.
Step 1: Use grep to find matching lines
First, use the grep command with the -n option to display line numbers:
bashgrep -n 'world' example.txt
The output will be:
shell1:hello world 3:hello world world 4:world hello 5:goodbye world
Step 2: Combine with awk to process the match count
Next, we can use awk to add the occurrence count of world at the end of each line. We pipe the output of grep into awk:
bashgrep -n 'world' example.txt | awk -F ':' '{print $0 " Count=" gsub(/world/, "&")}'
Here, the awk command does the following:
-F ':': Set the input field separator to colon (:), becausegrep -noutputs in the formatline number:line content.print $0 " Count=" gsub(/world/, "&"): Print the entire line content ($0) and append the occurrence count ofworld. Thegsub(/world/, "&")function replacesworldwith itself and returns the number of replacements, which is the match count.
The final output is:
shell1:hello world Count=1 3:hello world world Count=2 4:world hello Count=1 5:goodbye world Count=1
This gives us the line number, content, and the occurrence count of world on each line. This approach is ideal for processing log files or other scenarios where you need to count specific text occurrences.