Linux下統計某個目錄下所有源代碼行數的Shell腳本

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

 

 

發佈了185 篇原創文章 · 獲贊 136 · 訪問量 214萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章