Friday, May 18, 2012

How to count all the lines of code in a directory recursively?


We've got a PHP application and want to count all the lines of code under a specific directory and its subdirectories. We don't need to ignore comments, as we're just trying to get a rough idea.




wc -l *.php



That command works great within a given directory, but ignores subdirectories. I was thinking this might work, but it is returning 74, which is definitely not the case...




find . -name '*.php' | wc -l



What's the correct syntax to feed in all the files?


Source: Tips4all

11 comments:

  1. For another one-liner:

    ( find ./ -name '*.php' -print0 | xargs -0 cat ) | wc -l


    works on names with spaces, only outputs one number

    ReplyDelete
  2. You didn't specify how many files are there or what is the desired output.
    Is this what You are looking for:

    find . -name '*.php' | xargs wc -l


    ?

    ReplyDelete
  3. There is a little tool called sloccount to count the lines of code in directory. It should be noted that it does more than you want as it ignores empty lines/comments, groups the results per programming language and calculates some statistics.

    ReplyDelete
  4. For everyone stuck with windows:

    After I run into some problems counting lines of code under Windows, I found cloc.

    Serves the same purpose of sloccount but works flawlessly on Windows.

    ReplyDelete
  5. what you want is a simple for loop:

    total_count=0
    for file in $(find . -name *.php -print)
    do
    count=$(wc -l $file)
    let total_count+=count
    done
    echo $total_count

    ReplyDelete
  6. If you need just the total number of lines in let's say your PHP files you can use very simple one line command even under Windows if you have GnuWin32 installed. Like this:

    cat `/gnuwin32/bin/find.exe . -name *.php` | wc -l


    You need to specify where exactly is the find.exe otherwise the Windows provided FIND.EXE (from the old DOS-like commands) will be executed, since it is probably before the GnuWin32 in the environment PATH, and has different parameters and results.

    Please note that in the command above you should use back-quotes, not single quotes.

    ReplyDelete
  7. Yet another variation :)

    $ find -name '*.php' | xargs cat | wc -l

    ReplyDelete
  8. cat `find -name "*.php"` | wc -l


    should do the trick. This answer has been given again, sorry (missed the other answer link mine)..

    ReplyDelete
  9. very simply

    find /path -type f -name "*.php" | while read FILE
    do
    count=$(wc -l < $FILE)
    echo "$FILE has $count lines"
    done

    ReplyDelete
  10. cat \`find . -name "*.php"\` | wc -l

    ReplyDelete
  11. for sources only:

    wc `find`


    to filter, just use grep

    wc `find | grep .php$`

    ReplyDelete