1. 背景
本想用shell写个脚本统计一个java工程里的java代码行数,所以写了这个脚本,小弟基础还没学完,所以实现的比较粗糙,但是该脚本可以统计任何指定后缀的文件行数,比如(.java)后缀为统计java代码行数、(.sh)后缀统计shell脚本代码行数或者cpp等C++代码,使用请看第3节使用说明。
2. 实现思路
1、输入指定目录和文件后缀(如没有文件后缀,默认对所有文件行数统计) 2、进入目录下,生成一个随机命名的文件,作为当前进程正在统计的标志。 3、如果是文件,统计代码行数追加到一个【统计文件】内 4、该目录下所有文件统计完毕,删除一开始随机命名的文件 5、如果遇到目录,开一个后台进程重复步骤2、3、4。(其实就是一个递归) 6、回旋判断是否还有随机命名文件,直到没有证明所有进程统计完毕。 7、计算【统计文件】内的值,得到最后总行数
3. 使用说明
1、对指定后缀文件行数统计 . count_lines.sh {path} {suffix} 示例: . count_line.sh /mnt/g/shell/bash/ sh
对/mnt/g/shell/bash目录及其所有子目录,以.sh文件为后缀的代码行数统计 2、对所有文件行数统计 . count_lines.sh {path} 示例: . count_line.sh /mnt/g/shell/bash
对/mnt/g/shell/bash目录及其所有子目录下,所有文件的行数统计
4. 源码
#------------------------------------------------------
# Filename: count_line.sh
# Version: 1.0
# Date: 2017/9/26
# Author: Xiaodong Xu
# Email: 763795151@qq.com
# Description: count file lines with suffix, the first param is file path and the second param is file suffix
if [[ ! -d $1 ]];then
echo "the first argument is not a dircetory path..."
return;
fi
#if [[ x$2 == x ]];then
# echo "the second argument is a suffix and it is should not be null..."
# return;
#fi
root_path=$1
suffix=$2
cur_path=`pwd`
tmp_log="${cur_path}/tmp0123456789.log"
function count()
{
pid=$$
#generate a flag file
flag_file="${cur_path}/$RANDOM.count_flag"
touch $flag_file
total=0
cd $1
for file in `ls`
do
if [[ -d $file ]]; then
echo $file
count $file &
else
if [[ -f $file && ${file##*.} == $suffix ]]; then
let total+=`cat ${file} | wc -l `
else
if [[ -f $file && x$suffix == x ]]; then
let total+=`cat ${file} | wc -l `
fi
fi
fi
done
echo $total >> $tmp_log
rm $flag_file
}
count $root_path;
sleep 2
while [[ ! `find ${cur_path} -maxdepth 1 -name "*.count_flag" -print | wc -l` -eq 0 ]]
do
sleep 1
done
awk 'BEGIN { i=0 } { i+=$1 } END { printf("total lines: %s\n",i) }' $tmp_log
cd $cur_path
rm $tmp_log