Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


share|improve this question

migrated from Jul 5 '11 at 18:46

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

up vote 4 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

share|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 "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
find . -type d \
  \( -path ./public -o -path ./modules -o -path ./templates \) -prune \
  -o -type -f -print0 | xargs -0 wc
share|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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .