Search code examples
linuxfilecommand-linegrepwc

Count occurence of character in files


I want to count all $ characters in each file in a directory with several subdirectories. My goal is to count all variables in a PHP project. The files have the suffix .php.

I tried

grep -r '$' . | wc -c
grep -r '$' . | wc -l

and a lot of other stuff but all returned a number that can not match. In my example file are only four $. So I hope someone can help me.

EDIT

My example file

<?php
class MyClass extends Controller {

$a;$a;
$a;$a;
$a;
$a;

Solution

  • To recursively count the number of $ characters in a set of files in a directory you could do:

    fgrep -Rho '$' some_dir | wc -l
    

    To include only files of extension .php in the recursion you could instead use:

    fgrep -Rho --include='*.php' '$' some_dir | wc -l
    

    The -R is for recursively traversing the files in some_dir and the -o is for matching part of the each line searched. The set of files are restricted to the pattern *.php and file names are not included in the output with -h, which may otherwise have caused false positives.