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:

    loc [FLAGS] [OPTIONS] [target]...

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

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

    <target>...    File or directory to count

1 Answer 1


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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.