shell实现代码行数统计

shell实现代码行数统计

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. 源码

#! /bin/bash
#------------------------------------------------------
# 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不识君的荒漠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值