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

前端 未结 19 1434
耶瑟儿~
耶瑟儿~ 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 08:10

    There are many ways to do this, using common shell utilities.

    My solution is:

    grep -cve '^\s*$' 
    

    This searches for lines in the do not match (-v) lines that match the pattern (-e) '^\s*$', which is the beginning of a line, followed by 0 or more whitespace characters, followed by the end of a line (ie. no content other then whitespace), and display a count of matching lines (-c) instead of the matching lines themselves.

    An advantage of this method over methods that involve piping into wc, is that you can specify multiple files and get a separate count for each file:

    $ grep -cve '^\s*$' *.hh
    
    config.hh:36
    exceptions.hh:48
    layer.hh:52
    main.hh:39
    

提交回复
热议问题