Grep files containing two or more occurrence of a specific string

Since the question is tagged grep, here is a solution using only that utility and bash (no awk required):

#!/bin/bash
for file in *
do
  if [ "$(grep -c "Hello" "${file}")" -gt 1 ]
  then
    echo "${file}"
  fi
done

Can be a one-liner:

for file in *; do if [ "$(grep -c "Hello" "${file}")" -gt 1 ]; then echo "${file}"; fi; done

Explanation

  • You can modify the for file in * statement with whatever shell expansion you want to get all the data files.
  • grep -c returns the number of lines that match the pattern, with multiple matches on a line still counting for just one matched line.
  • if [ ... -gt 1 ] test that more than one line is matched in the file. If so:
  • echo ${file} print the file name.

What about this:

grep -o -c Hello * | awk -F: '{if ($2 > 1){print $1}}'

Tags:

Unix

Grep