views:

1895

answers:

7

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?

+2  A: 

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

?

Reef
This will work, as long as there are not too many files : if there are a lot of files, you will get several lines as a result (xargs will split the files list in several sub-lists)
Pascal MARTIN
ah, yes. That's why I said He didn't specify how many files are there. My version is easier to remember, but Shin's version is better if You have more than a few files. I'm voting it up.
Reef
+11  A: 

Try

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

This may help as well

http://www.dwheeler.com/sloccount/

It'll give an accurate source lines of code count for whatever hierarchy you point it at, as well as some additional stats

Peter Elespuru
Thanks. It worked perfectly!
+2  A: 

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
ennuikiller
isn't this overkill compared to the answers that suggest `xargs`?
Nathan Fellman
No, Nathan. The xargs answers won't necessarily print the count as a single number. It may just print a bunch of subtotals.
Rob Kennedy
what will this program do if file names contain spaces? What about newlines? ;-)
Reef
+1  A: 

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.

sebasgo
+4  A: 

For another one-liner:

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

works on names with spaces, only outputs one number

Shin
+1 for `-print0`/`-0`
Dennis Williamson
A: 

very simply

find /path -type f -name "*.php" | while read FILE
do
    count=$(wc -l < $FILE)
    echo "$FILE has $count lines"
done
ghostdog74
it will fail if there is a space or a newline in one of the filenames
Reef
A: 

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

Bjarni Herjolfsson