in reply to search text file

This shell command almost works, but not quite: it actually counts the number of lines each string matches, so if a string can occur more than once in a line you'll get a wrong answer.

( while read; do grep -cFe "$REPLY" secondfile; done ) < firstfile

Replies are listed 'Best First'.
Re^2: search text file
by jwkrahn (Abbot) on Jul 27, 2011 at 10:45 UTC

    To count all the matches from the command line:

    grep -oF -f firstfile secondfile | sort | uniq -c

      Ah, good idea using grep -o. That does indeed find multiple matches in a single line.

      That, however, won't work correctly if some of the matches are overlapping. Eg. if the second file has abcdef and the first file has the two strings abcd and cdef, grep will only find the abde part. As a workaround, you could run grep once for each string in the first file. Thus, we get (I think)

      ( while read; do grep -oFe "$REPLY" secondfile | wc -l; done ) < first +file