Code Counter





7
Date Submitted Thu. Sep. 14th, 2006 1:45 PM
Revision 1 of 1
Helper dohpaz
Tags bash | Code | Comments | Grep | Sed
Comments 0 comments
I found this script online, and decided that I would modify it for my needs. As a developer, I like to know how many actual lines of code I have written--not including any comments.

It outputs in a very simple way:

Including Comments: NNN
Without Comments: NNN

One very practical, and quick, way to determine how many lines of code a project has is to pipe it through a find:


find /usr/share/php -name "*.php" -o -name "*.inc" | xargs count-code


If your code is in files of another type (i.e., .c, .h, .cpp, etc), then simply change the extensions and add more '-o -name "*.ext"' tags. If you have directories that you don't want to be counted, simple throw a "| grep -v [path/to/excluded/directory] |" inbetween the find and the xargs, and they will not be counted.

#!/bin/sh
# Count lines of C, C++, Java, or C# code, excluding comments and blank lines.
#
# Originally obtained from:
#   http://www.cs.cornell.edu/courses/cs114/2004fa/notes/lec8.html, 2004-10-15
#
# 2006-09-14: Ken Stanley
# 1. Modified the code to print out a comparison of lines between the commented
#    code and then the code if the comments were to be removed.
# 2. Now it will exclude all comments that start with a #, except if the
#    comment happens to be something like "#!/bin/sh" which is not a comment.
#

echo -en "Including comments:\t";
WITHCOMMENTS=`cat $* | wc -l`;
echo "$WITHCOMMENTS";

# Order of operation:
#       1. Strip C++ // comments
#       2. Replace @ and % with + and newline with @
#       3. Replace */ with %
#       4. Strip /* ... %
#       5. Restore newlines
#       6. Strip blank lines: [] contains a tab and space
#       7. Strip all bash-style comments
#       8. Count the remaining lines
echo -en "Without comments:\t";
WITHOUTCOMMENTS=`sed -e 's!//.*$!!' $* | tr '@%\012' '++@' | sed -e 's!\*/!%!g' | sed -e 's!/\*[^%]*%!!g' | tr @ '\012' | grep -v '^[  ]*$' | grep -v '^#[^!].*$' | wc -l`;
echo -en "$WITHOUTCOMMENTS\n\n";
 

Ken S

Comments

There are currently no comments for this snippet.

Voting