I want to count the lines of all files in this directory and all its subdirectories, but exclude directories "public", "modules", and "templates".

How?

link|improve this question

74% accept rate
feedback

migrated from stackoverflow.com Jul 5 '11 at 18:46

This question came from our site for professional and enthusiast programmers.

2 Answers

up vote 3 down vote accepted
 find . -type f |grep -v "^./public" |grep -v "^./modules"|grep -v "^./templates"|xargs cat |wc -l
  1. make a list of all files under current directory with find . -type f
  2. filter out files from "exclude" dirs with grep -v
  3. xargs will read list of files from stdin and pass all files as options to cat.
  4. cat will print all files to stdout
  5. wc will count lines.

If you want to count lines in every file individually, change xargs cat |wc -l to xargs wc -l

link|improve this answer
Casper's solution is nicer, avoiding the grep -v. – jfgagne Aug 10 '11 at 18:47
jfgagne, If you consider his solution as better, upvote it. My solution is easier to understand and to modify - I think it is better to begginner. Casper's needs a deep knowledge of the find command, and my needs only basic options of find, grep, xargs, wc. – osgx Aug 10 '11 at 19:23
Also, -print0 is unportable, according to pubs.opengroup.org/onlinepubs/009695399/utilities/find.html "Other implementations have added other ways to get around this problem, notably a -print0 primary that wrote filenames with a null byte terminator. This was considered here, but not adopted. " – osgx Aug 10 '11 at 19:26
feedback
find . -type d \
  \( -path ./public -o -path ./modules -o -path ./templates \) -prune \
  -o -type -f -print0 | xargs -0 wc
link|improve this answer
As osgw pointed out, using -print and piping to xargs cat | wc -l might be more portable, but I like avoiding many greps and avoiding going down uselessly in directories. If you do not have read permission on those directories, lots of warning are avoided. +1, and I think it should be the accepted solution. – jfgagne Aug 10 '11 at 19:46
feedback

Your Answer

 
or
required, but never shown

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