grep - use case 1
Consider a scenario in which a directory (such as a log directory) has files created by an outside program. Your task is to write a shell script that determines which (if any) of the files that contain two occurrences of a string, after which additional processing is performed on the matching files.
One solution involves the – c option for grep , followed by additional invocations of the grep command.
The file hello1.txt contains the following:
hello world1
The file hello2.txt contains the following:
hello world2
hello world2 second time
The file hello3.txt contains the following:
hello world3
hello world3 two
hello world3 three
$ grep -c hello hello*txt | grep ":2$" hello2.txt:2
Note how we use the “ends with” $ metacharacter to grab just the files that have exactly two matches. We also use the colon :2$ rather than just 2$ to prevent grabbing files that have 12, 32, or 142 matches (which would end in :12, :32 and :142).
What if we wanted to show “two or more” (as in the “2 or more errors in a log”)? In this case, you would use the invert ( -v ) command to exclude counts of exactly 0 or exactly 1.
$ grep -c hello hello*txt | grep -v ':[0-1]$' hello2.txt:2 hello3.txt:3