• 2

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 190


File: /var/www/stackquestions.com/public_html/application/views/question.php
Line: 190
Function: _error_handler

File: /var/www/stackquestions.com/public_html/application/controllers/Questions.php
Line: 416
Function: view

File: /var/www/stackquestions.com/public_html/index.php
Line: 315
Function: require_once

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?

Surprisingly there's no answer based on find's -exec and awk. Here we go:

find . -type f -exec wc -l {} ; | awk '{ SUM += $0} END { print SUM }'

This snippet finds for all files (-type f). To find by file extension, use -name:

find . -name '*.py' -exec wc -l '{}' ; | awk '{ SUM += $0; } END { print SUM; }'
  • 0
Reply Report

If you're using it often, modify it to suit and put it in a script.

This example:

  1. Properly excludes paths that aren't your code (not traversed at all by find)
  2. Filters out compound extensions and other files you wish to ignore
  3. Only includes actual files of the types you specify
  4. Ignores blank lines
  5. Gives a single number as a total
find . ! ( ( -path ./lib -o -path ./node_modules -o -path ./vendor -o -path ./any/other/path/to/skip -o -wholename ./not/this/specific/file.php -o -name '*.min.js' -o -name '*.min.css' ) -prune ) -type f ( -name '*.php' -o -name '*.inc' -o -name '*.js' -o -name '*.scss' -o -name '*.css' ) -print0 | xargs -0 cat | grep -v '^$' | wc -l
  • 0
Reply Report


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

The SLOCCount tool may help as well.

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

Sorted output: find . -name '*.php' | xargs wc -l | sort

  • 2
Reply Report