UNIX Count total number of lines in all files recursively

Recently I have been working on a fairly large product alongside one other developer and out of interest was keen to discover roughly how many lines of code we had written between us.

The following snippets use the wc command and can be run on the command line to output the total number of new line characters present in all files within a directory recursively.

wc -l `find /path/to/directory/ -type f`

This will output results in the following format, showing the number of lines for each file:

[root@server ~]# wc -l `find /path/to/directory/ -type f`
 103 /path/to/directory/a.php
 378 /path/to/directory/b/c.xml
 132 /path/to/directory/d/e.xml
 613 total

Alternatively, to output just the total number of new line characters without the file by file counts to following command can prove useful:

find /path/to/directory/ -type f -exec wc -l {} \; | awk '{total += $1} END{print total}'

The output for this is a single numeric value, in this case 613:

[root@server ~]# find /path/to/directory/ -type f -exec wc -l {} \; | awk '{total += $1} END{print total}'
 613

As always, there are many different methods that could be used to achieve the same results mentioned here, I just found these to be quick and sufficient for providing the rough estimates we needed.

6 Replies to “UNIX Count total number of lines in all files recursively”

  1. I have one .csv file in unix. It contains some records. I have found that error came on some of line. but don’t have line numbers in a file. I want to extract that specific line for issue resolve. how to do that?

    Eg: file.csv with 30000 records in it.but without line numbers specified.
    Error: 25578 line number
    i want to view contents on that line.

    1. @sunnychangediya probably late but might help someone else… “vi +25578 file.csv” will open the file in vim, right on that line.. If you want to see line numbers once you open vi (and if they are not already there) just type “:set nu”.

Leave a Reply