MadanRevoor.com | Aesthetic Web design using Wordpress and JQuery | { This site sponsored by Gatwick Airport Parking }
In this post, I’m going to showcase a small shell script that can count the number of lines in a file and will recursively move through all sub directories and list the count of lines in all files within them. This script helped me during the analysis phase of a project where I had to provide estimates for development based on complexity metrics which was indirectly tied up to the count of lines, the number of files and number of database tables used by each program. This script shall only count the number of lines in a file recursively and display them.
#!/bin/bash
DIR="." #assigns the current path to this variable
# This function does the work of checking every input
# parameter to test if its a directory or file. If it is a directory
# it recursively calls itself to count the lines of all files within it.
# Else, if it is a file, it invokes 'wc' to print the number of lines in
# that file and stops.
count_lines()
{
if [ ! -d "$1" ]
then
echo "$1"
return
fi
cd "$1"
for file in *
do
if [ -d "$file" ]
then
count_lines "$file"
cd ..
else
count=`wc -l "$file" | cut -d ' ' -f1`
echo "$PWD/$file: $count lines"
fi
done
}
# Main Processing starts here. If no inputs
# offered, run the script on the files in the
# current directory.
if [ $# -eq 0 ]
then
count_lines $DIR # if no input offered, count_lines of files in current directory
exit 0
fi
# For every input parameter passed to this script,
# count lines of all files within each of them.
for i in $*
do
DIR="$1"
count_lines "$DIR"
shift 1 #Consider the next input parameter
done
Hope you find this script useful. If you have any suggestions, please feel free to offer them. Thanks!
This entry was posted on Saturday, October 17th, 2009 at 12:02 pm and is filed under Linux. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
This is good. The logic in your code is hard to follow. Comments would have helped me. Any reason you did not choose PERL or PYTHON ?
Thanks. I have updated the script with explanations. I was planning to add them soon but got caught up with something else. I’m used to shell programming and hence used it. I have not had a chance to explore PERL or PYTHON so far. I would love to learn them soon.