Search code examples
bashshellwc

Searching for .extension files recursively and print the number of lines in the files found?


I ran into a problem I am trying to solve but can't think about a way without doing the whole thing from the beginning. My script gets an extension and searches for every .extension file recursively, then outputs the "filename:row #:word #". I would like to print out the total amount of row #-s found in those files too. Is there any way to do it using the existing code?

for i in find . -name '*.$1'|awk -F/ '{print $NF}'
do
  echo "$i:`wc -l <$i|bc`:`wc -w <$i|bc`">>temp.txt
done

sort -r -t : -k3 temp.txt

cat temp.txt

Solution

  • This is a one-liner printing the lines found per file, the path of the file and at the end the sum of all lines found in all the files:

    find . -name "*.go" -exec wc -l {} \; | awk '{s+=$1} {print $1, $2} END {print s}'
    

    In this example if will find for all files ending *.go then will execute use wc -l to get the number of lines and print the output to stdout, awk then is used to sum all the output of column 1 in the variable s the one will be only printed at the end: END {print s}

    In case you would also like to get the words and the total sum at the end you could use:

    find . -name "*.go" -exec wc {} \; | \
        awk '{s+=$1; w+=$2} {print $1, $2, $4} END {print "Total:", s, w}'
    

    Hope this can give you an idea about how to format, sum etc. your data based on the input.