Ubuntu – How would you count every occurrence of a term in all files in the current directory

command linedirectoryfilesgrep

How would you count every occurrence of a term in all files in the current directory? – and subdirectories(?)

I've read that to do this you would use grep; what is the exact command?

Also, is it possible to the above with some other command?

Best Answer

Using grep + wc (this will cater for multiple occurences of the term on the same line):

grep -rFo foo | wc -l
  • -r in grep: searches recursively in the current directory hierarchy;
  • -F in grep: matches against a fixed string instead of against a pattern;
  • -o in grep: prints only matches;
  • -l in wc: prints the count of the lines;
% tree                 
.
├── dir
│   └── file2
└── file1

1 directory, 2 files
% cat file1 
line1 foo foo
line2 foo
line3 foo
% cat dir/file2 
line1 foo foo
line2 foo
line3 foo
% grep -rFo foo | wc -l
8