Server Side

Server related posts

Count lines of code in a Linux directory

Written by: Peter Fisher on July 6, 2012
Tagged under: , ,
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Linux penguin Tux

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

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Peter Fisher is a web developer working in Gloucester UK. Founder of the digital agency Websomatic, author of this blog and the HowToCodeWell Youtube channel. Peter has over ten years of web development experience under his belt

Read all about Peter Fisher

Leave a Reply

Your email address will not be published. Required fields are marked *