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条回答
forever°为你锁心
2楼-- · 2019-01-20 22:27
rgrep . | wc -l

gives the count of non blank lines in the current working directory.

甜甜的少女心
3楼-- · 2019-01-20 22:29

If you want to use something other than a shell script, try CLOC:

cloc counts blank lines, comment lines, and physical lines of source code in many programming languages. It is written entirely in Perl with no dependencies outside the standard distribution of Perl v5.6 and higher (code from some external modules is embedded within cloc) and so is quite portable.

Melony?
4楼-- · 2019-01-20 22:31
#!/bin/bash
find . -path './pma' -prune -o -path './blog' -prune -o -path './punbb' -prune -o -path './js/3rdparty' -prune -o -print | egrep '\.php|\.as|\.sql|\.css|\.js' | grep -v '\.svn' | xargs cat | sed '/^\s*$/d' | wc -l

The above will give you the total count of lines of code (blank lines removed) for a project (current folder and all subfolders recursively).

In the above "./blog" "./punbb" "./js/3rdparty" and "./pma" are folders I blacklist as I didn't write the code in them. Also .php, .as, .sql, .css, .js are the extensions of the files being looked at. Any files with a different extension are ignored.

查看更多
家丑人穷心不美
5楼-- · 2019-01-20 22:31

There's already a program for this on linux called 'wc'.

Just

wc -l *.c 

and it gives you the total lines and the lines for each file.

查看更多
一纸荒年 Trace。
6楼-- · 2019-01-20 22:33

Script to recursively count all non-blank lines with a certain file extension in the current directory:

#!/usr/bin/env bash
(
echo 0;
for ext in "$@"; do
    for i in $(find . -name "*$ext"); do
        sed '/^\s*$/d' $i | wc -l ## skip blank lines
        #cat $i | wc -l; ## count all lines
        echo +;
    done
done
echo p q;
) | dc;

Sample usage:

./countlines.sh .py .java .html
查看更多
迷人小祖宗
7楼-- · 2019-01-20 22:34

This command count number of non-blank lines in our project.
cat fileName | grep -v ^$ | wc -l
grep -v ^$ regular expression function is ignore blank lines.

登录 后发表回答