Counting lines of code

With Ohloh reporting Drupal core to have roughly 25k lines of code, I was curious to determine how many lines of code were in some of my projects (useful to estimate costs). Finding this out wasn’t nearly as easy as I thought and after the past hour+ of Googling, testing, and resting, I found the following command to work the best for counting lines of code in a Drupal project—-at least for me on OSX that is. Enjoy!

  1. find . \( -name '*.module'
  2.   -o -name '*.inc'
  3.   -o -name '*.php'  
  4.   -o -name '*.css'
  5.   -o -name '*.js' \) -exec cat -- {} \; | wc -l

You want to google for

You want to google for sloccount

You can use -regex with find

You can use -regex with find to get a more reasonable matching tool, but unfortunately it defaults to emacs.

find -regextype posix-egrep -regex ‘.*(module|inc|php|css|js)$’

Also, if you want to skip completely blank lines, you can “egrep .”. I usually use “xargs” rather than -exec, as it batches up the commands into lumps with multiple parameters.

find -regextype posix-egrep -regex ‘.*(module|inc|php|css|js)$’ | xargs grep . | wc -l

YMMV

Note that this will count

Note that this will count the comment lines too. Sometimes, these are not counted in metrics.

As for what else to use to count lines of code, check this on Wikipedia.

Indeed. All very good points

Indeed. All very good points guys.

I will admit, I am no command line guru. But for a quick estimate, this command worked extremely well.

For more detailed reports, I’ll certainly have to refine my technique and will post any updates for what works and doesn’t. Sounds like Gerhard’s recommended program might be a winner ;-)

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You can use Textile markup to format text.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <p> <img> <pre>
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options