In this post I demonstrate how to count the lines of code in a directory and its sub directories using the wc command in Linux.
It always interests me to know how many lines of code I have written for a project or how many lines of code I may of reduced after refactoring some logic. You can install CLI/GUI applications to aid in this task. One of which is the Perl program SLOCCount which can give you a breakdown of languages and lines of code found.
However for this post I will just be using the pre installed commands that Linux comes with. Below is a one liner that recursively searches for any filenames with the extension .php and passes the output to the wc command.
Lets break this up and look at the command in chunks to get a better idea of what is going on
Step One: find all the files
The find command is running on the current working directory (.) and looking for any files within this folder and sub folders which have a name ending in .php. The (*) wildcard in the search expression means that any file will be found as long as it ends with .php. You could alter this search expression to get any kind of file or filename.
Step Two: Act on the output of the find command
Running the find command above will return a standard output (stdout) which lists all the files found based on the search expression supplied destination. What we need to do is pass each of these filenames to the wc command which will count the lines within the file. To do this we pipe (|) the output to the xargs command which in turn executes the wc command based on the file supplied.
Below is the output from the command which shows I have written twenty lines of code in a test project