Read more

Grep the number of occurences in a file, counting multiple hits per line

Arne Hartherz
August 09, 2011Software engineer at makandra GmbH

Grep prints one line per match. To return the number if matches, use the -c switch:

grep -c "something" filename
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

However, if a word appears more than once in a line, it is only counted once.

To count every match, you can use sed Show archive.org snapshot to force line breaks on multiple matches:

sed 's/something/something\n/g' filename | grep -c "something"
Posted by Arne Hartherz to makandra dev (2011-08-09 22:25)