count (non-blank) lines-of-code in bash

2019-01-20 22:09发布

In Bash, how do I count the number of non-blank lines of code in a project?

17条回答
可以哭但决不认输i
2楼-- · 2019-01-20 22:45

If you want the sum of all non-blank lines for all files of a given file extension throughout a project:

while read line
do grep -cve '^\s*$' "$line"
done <  <(find $1 -name "*.$2" -print) | awk '{s+=$1} END {print s}'

First arg is the project's base directory, second is the file extension. Sample usage:

./scriptname ~/Dropbox/project/src java

It's little more than a collection of previous solutions.

查看更多
SAY GOODBYE
3楼-- · 2019-01-20 22:48

'wc' counts lines, words, chars, so to count all lines (including blank ones) use:

wc *.py

To filter out the blank lines, you can use grep:

grep -v '^\s*$' *.py | wc

'-v' tells grep to output all lines except those that match '^' is the start of a line '\s*' is zero or more whitespace characters '$' is the end of a line *.py is my example for all the files you wish to count (all python files in current dir) pipe output to wc. Off you go.

I'm answering my own (genuine) question. Couldn't find an stackoverflow entry that covered this.

查看更多
做个烂人
4楼-- · 2019-01-20 22:49
grep -v '^\W*$' `find -type f` | grep -c '.' > /path/to/lineCountFile.txt

gives an aggregate count for all files in the current directory and its subdirectories.

HTH!

查看更多
贼婆χ
5楼-- · 2019-01-20 22:50
cat foo.c | sed '/^\s*$/d' | wc -l

And if you consider comments blank lines:

cat foo.pl | sed '/^\s*#/d;/^\s*$/d' | wc -l

Although, that's language dependent.

查看更多
你好瞎i
6楼-- · 2019-01-20 22:50

It's kinda going to depend on the number of files you have in the project. In theory you could use

grep -c '.' <list of files>

Where you can fill the list of files by using the find utility.

grep -c '.' `find -type f`

Would give you a line count per file.

查看更多
登录 后发表回答