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

前端 未结 19 1436
耶瑟儿~
耶瑟儿~ 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:50

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

    0 讨论(0)
  • 2020-12-07 07:50
    cat 'filename' | grep '[^ ]' | wc -l
    

    should do the trick just fine

    0 讨论(0)
  • 2020-12-07 07:52

    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.

    0 讨论(0)
  • 2020-12-07 07:52

    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.

    0 讨论(0)
  • 2020-12-07 07:53

    '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.

    0 讨论(0)
  • 2020-12-07 07:53

    This gives the count of number of lines without counting the blank lines:

    grep -v ^$ filename wc -l | sed -e 's/ //g' 
    
    0 讨论(0)
提交回复
热议问题