您的位置:首页 > 运维架构 > Shell

Linux下统计某个目录下所有源代码行数的Shell脚本

2010-12-16 14:41 465 查看
PS:
找到一个简单的方法:

wc -l `find ./ -name "*.c"` wc -l `find ./ -name "*.h"`

其他语言也类似: *.cpp,*.java,*.py,*.rb,*.js etc.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

由于要统计某个源代码下的所有代码的行数,所以这里自己写了个脚本来完成这个功能。我在编写这个脚本的时候,遇到了一些问题,我先把代码贴在这里;

使用方法,将此脚本文件存为linesNumber.sh,使用时,在后面跟上指定目录即可,例如:
# ./linesNumber.sh mplayer
就是统计mplayer目录下的所有.cpp,.c,.h文件的源代码行数;
对于你还需要增加其他的行数,你只需更改教本中的REG变量即可,更改方法参考REG变量内容,对应修改即可;

/**************************************************/

#! /bin/sh
# writed by lsosa for counting the number of all the source code;
# example ./linesNumber.sh .

# usage info;
USAGE="Usage:/t./linesNumber.sh ./n"
# help info;
HELP="You can count the number of lines of the specified directory by this script/n${USAGE}"
# the tmp file to save the number of lines;
COUNT_TMP_FILE=/tmp/count
# this filter can get all the *.cpp *.c *.h files from your source code tree;
REG='/.cpp$|/.c$|/.h$'

# show usage when you use this script with some incorrect way;
show_usage(){
echo -ne ${HELP}
}

# function to count lines of all your source code tree;
count_lines(){
# excluding the error;
if [ $# -lt 1 ]
then
echo "Usage: count_lines $1"
return 1
fi
# start to count the number of lines;
_DIR=$1
echo "Start to count the number of lines in current directory ${_DIR}"
find ${_DIR} -name "*" | grep -E ${REG} | /
while read LINE
do
NUMLINES=`cat ${LINE} | wc -l`
echo ${LINE}:${NUMLINES}
NUM=`expr ${NUM} + ${NUMLINES}`
echo ${NUM} > ${COUNT_TMP_FILE}
done
echo "The number of all the lines are:"
cat ${COUNT_TMP_FILE}
rm -f ${COUNT_TMP_FILE}
echo "Counting Finished"
}

# main;
main(){
if [ ! $# = 1 ]
then
# show help about this script;
show_usage
exit 1
else
# start to count lines;
count_lines $1
fi
}

# call main;
main $1

/**************************************************/

主要是两个问题:
一、
while循环内部变量NUM存储的是每一次累加的文件行数值,但是这个值不能够在while循环外使用,这会给编写脚本的人造成极大的不便,这个问题,我是绕过解决的,并没有找到更合适的类似C或者C++对其直接支持的方法;我是将每次的累加值存储到那个临时文件(/tmp/count)中,最后显示这个文件中的值就是总行数,这样就让过了while循环内部变量不能在循环外使用的局限;不知道各位有什么好的方法没有;
二、
函数内部并不能够直接使用shell传给脚本的参数,你可以检测一下,对于$1,$#都是空或0。这里的解决方法比较简单了,就是将shell的参数传给函数即可,shell中函数调用参数很简单,将参数罗列排在函数名后面即可;函数要使用参数也只需要使用$1-$9调用即可,这种使用方法同shell主脚本的;
最后,还有个疑问吧,就是shell使用变量似乎不用定义,直接使用即可,初始化都是个空串,随你后面怎么使用而变化,你当数字使用,它就存数字,当字符串使用,它就存字符串;这一点很方便,但也容易造成混淆,这就看咱们的使用习惯了,呵呵。。。


From: http://blog.csdn.net/baymoon/archive/2007/01/11/1480065.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: