grep -c is useful for finding how many times a string occurs in a file, but it only counts each occurence once per line. How to count multiple occurences per line?I'm looking for something more elegant than:perl -e '$_ = <>; print scalar ( () = m/needle/g ), \n'
Count total number of occurrences using grep
grep
grep's -o will only output the matches, ignoring lines; wc can count them:grep -o 'needle' file | wc -lThis will also match 'needles' or 'multineedle'.Only single words:grep -o '\bneedle\B' file | wc -l# or:grep -o '\<needle\>' file | wc -l