Skip to content

Instantly share code, notes, and snippets.

@silverweed
Last active October 18, 2024 09:56
Show Gist options
  • Save silverweed/9d4bc73c8d96a012e8bc95f3d3a72653 to your computer and use it in GitHub Desktop.
Save silverweed/9d4bc73c8d96a012e8bc95f3d3a72653 to your computer and use it in GitHub Desktop.
Simple bash script to count effective lines of code for several types of languages
#!/bin/bash
# count lines of code, excluding comments and empty lines.
# (c) silverweed - released under Public Domain
comment_style() {
local CS=''
case $1 in
c|cpp|cs|java*|js) CS='^\s*//|^\s*\*|^\s*/\*' ;;
sh|bash|zsh|ruby|py*) CS='^\s*#' ;;
lua) CS='--' ;;
hs|haskell) CS='--|^\s*{-'
esac
[[ -n $CS ]] && echo "(^\\s*$|$CS)" || echo '^\s*$'
}
COMMENT_STYLE=$(comment_style c)
while [[ $# > 0 ]]; do
case $1 in
-h) echo "Usage: $0 [-e ext] [-c <comment-style, default=c>] [--exclude path] [dir]" >&2; exit 0 ;;
-e) shift; EXT=$1; shift ;;
-c) shift; COMMENT_STYLE=$(comment_style $1); shift ;;
--exclude) shift; EXCLUDE="-not -path $1"; shift ;;
*) DIR+="$1 "; shift ;;
esac
done
DIR=${DIR:-.}
find $DIR -type f -name \*$EXT $EXCLUDE -exec grep -cvE $COMMENT_STYLE {} + |
tee >(awk -v FS=':' '{printf "%-5d %s\n", $2, $1}' | sort -g >&2) |
cut -f2 -d: |
awk '{ n += $1 } END { print n }'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment