3

So, I have a GitHub repository that I want to display the lines of code of the project on. So, I found a tool called loc (lines of code) here. In the tool, it outputs the lines of code like so:

--------------------------------------------------------------------------------
Language             Files        Lines        Blank      Comment         Code
--------------------------------------------------------------------------------
C++                      1          567           29           22          516
C/C++ Header             2          245           12           15          218
--------------------------------------------------------------------------------
Total                    3          812           41           37          734
--------------------------------------------------------------------------------

Is there any way that I could grep only the Total row in the Code column? The options for the loc command only consist of this:

USAGE:
    loc [FLAGS] [OPTIONS] [target]...

FLAGS:
        --files      Show stats for individual files
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
        --exclude <REGEX>    Rust regex of files to exclude
        --include <REGEX>    Rust regex matching files to include. Anything not matched will be excluded
        --sort <COLUMN>      Column to sort by

ARGS:
    <target>...    File or directory to count
0

1 Answer 1

2

You can do this easily with grep, but you need two steps:

  1. Filter the line that contains Total:

    grep 'Total'
    
  2. Display only the last number (consecutive digits) from that line:

    grep -Po '\d+$'
    

    -P switches to PCRE regex mode, which is needed for it to understand that \d means "any digit (0-9)".
    -o tells it to only display the matched sequence, not the whole line.
    $ matches the end of the line.

Together these snippets make up the command below:

loc | grep 'Total' | grep -Po '\d+$'

If we assume you have a plain text file containing a line like this:

Current lines of code in this project: 123

You can edit this file and replace the number in this line with the value stored in the Bash variable $linecount using the sed command below. Of course you must store the total line count in that variable first, like this:

linecount=$(loc | grep 'Total' | grep -Po '\d+$')

sed -i -E "s/(Current lines of code in this project: )[[:digit:]]+/\1$linecount/" README.MD
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .