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

前端 未结 19 1437
耶瑟儿~
耶瑟儿~ 2020-12-07 07:14

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

相关标签:
19条回答
  • 2020-12-07 07:55
    awk '/^[[:space:]]*$/ {++x} END {print x}' "$testfile"
    
    0 讨论(0)
  • 2020-12-07 08:03
    cat file.txt | awk 'NF' | wc -l
    
    0 讨论(0)
  • 2020-12-07 08:04
    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.

    0 讨论(0)
  • 2020-12-07 08:05
    grep -cvE '(^\s*[/*])|(^\s*$)' foo
    
    -c = count
    -v = exclude
    -E = extended regex
    '(comment lines) OR (empty lines)'
    where
    ^    = beginning of the line
    \s   = whitespace
    *    = any number of previous characters or none
    [/*] = either / or *
    |    = OR
    $    = end of the line
    

    I post this becaus other options gave wrong answers for me. This worked with my java source, where comment lines start with / or * (i use * on every line in multi-line comment).

    0 讨论(0)
  • 2020-12-07 08:05

    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
    
    0 讨论(0)
  • 2020-12-07 08:06

    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.

    0 讨论(0)
提交回复
热议问题