• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4460
  • Last Modified:

counting lines of code using grep | wc -l


I want to count the number of lines of code in my code base.

I am thinking of doing something like:

grep –R “;” * | wc –l

except that counts all files (and I only want .h and .cpp).

How do I recursively count the number of lines in my code (roughly using the semi-colon)?

Thanks. =)

  • 2
1 Solution
You could use the 'find' command to filter the files found.
You could also cheat a bit with this (matches the filename
extension on the filename that grep prepends to the lines):

grep -H –R “;” * | grep -E "\.((h)|(cpp)):" | wc –l

grep -c ';' *.h -r; grep -c ';' *.cpp -r
No capncrunch_321 that won't work. The -r will work for the glob pattern you give... And at least I am not in the habit of naming my source directories foo.cpp;-).
bretmjonsons "el cheapo" grep relies on some flags that not all incarnation of grep has... (The -R was introduced between 2.4.2 and 2.5.1 version of GNU grep, so safer to use the --longstyle options:-)...
If one wants a version that'll work on most any unix/linux one will have to look to the find|xargs grep|wc thing mentioned in part by brettmjohnson... Something like
find /path/to/sourcedir -name \*.cpp -print -o -name \*.h -print | xargs grep ';' | wc -l

-- Glenn
.... And note that macros (defines, ifdefs etc), and complex multiline function defines/calls aren't counted correctly here, nor are any "commented" lines that happen to contain a ";" excluded.
Might be more correct to just count 'em all and perhaps do a simple estimate as to the "comment&whitespace density";-).

-- Glenn

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now