利用shell和awk筛选出所有函数定义和声明的地方,并记录文件名和行号

来源:互联网 发布:堡垒之夜 知乎 编辑:程序博客网 时间:2024/06/03 18:56

Shell script

PROJECT_DIR=~/Documents/Computer_science/Source_code/C/openssh-2.2.0p1/

SOURCE_FILE_LIST=~/Documents/Computer_science/Source_code/Bash/AWK/file_list
OUTPUT_FILENAME=/home/Ken/Documents/Computer_science/Source_code/Bash/AWK/output.out
echo -n '' > ${OUTPUT_FILENAME}
if [[ ! -e ${SOURCE_FILE_LIST} ]]
then
    echo "CREATING source file list"
    find ${PROJECT_DIR} -name '*.[c, h]' > ${SOURCE_FILE_LIST}
fi

while read file_name
do
    if [[ ${file_name} =~ ^[[:space:]]*return || ${file_name} =~ ^[[:space:]]*else[[:space:]]+if ]]
    then
        continue
    fi  
    awk -f const.awk -v OUTPUT_FILE=${OUTPUT_FILENAME} ${file_name}
done < ${SOURCE_FILE_LIST}
~                                                                                                                              
~                           


awk script


BEGIN \
{
    OFS=":"
}

#patter1:

#in the following line, `\)?' is added only because gawk will complain, if without it
/^\s*extern.*\s+\w+\s*\(\)?.*/ || /^\s*\w+\s+\w+\s*\(\)?/ \
{
    if ($1 != "return" && $1 != "typedef" && $1 != "else")
#exclude 'return func_name()', 'typedef void func_ptr()' and 'else if func_name()'
        print $0, FILENAME, FNR >> OUTPUT_FILE
}

#patter2:
#for the sake of this type of declaration:
#       unsigned int
#           hello(int a);

/^(\s*\w+)+$/ \
{
    if (index($1, "#") == 0 && $0 !~ /^\s*\/\// && index($0, "*/") == 0 && $1 !~ /\<(if|else|struct|typedef|while|do|\{|\}|return)\>/)

    # first one protects against preprocessing directives, second and the third against comments, the last one against some keywords
    {
        getline
        if ($0 ~ /^\s*\w+\s*\(\)?/)
            print $0, FILENAME, FNR >> OUTPUT_FILE
    }
}

0 0
原创粉丝点击