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

使用shell脚本统计源码文件中的注释行数.(// , /**/)

2012-08-10 20:33 806 查看
今天看到一求助帖子再问这个事,所以无聊写了个。

用的是awk脚本 , 也就是脚本解释器是用/usr/bin/awk , 而不是/bin/sh

但都是脚本 , 如果你想的话,

可以用shell脚本调用我这个awk脚本就行了。

使用方法:将下面的脚本保存成文件如get-cfile-notes.awk

然后chmod 755 get-cfile-notes.awk就可以运行了。

注意:

因为在这种脚本里面没什么好的方法使用栈和逐字符的处理,所以只能处理简单的情况 。 比如一行中出现/* xxxxdfafw */ /* jwo*/ /* */ 等等。

但只要你不是故意要考倒我的这个程序,基本使用是没问题的。

如下:

#!/usr/bin/awk -f

# 本程序用来统计c文件中的注释的行数
# by fdl19881
# 2012.8.10

BEGIN {
num_notes = 0;
stat = 0; # 0:无注释, 1://注释(notes1) , 2:/* */注释(notes2)
}

{
if(stat ==  0) {
notes1 = match($0 , /\/\//); # 查找//位置
notes21 = match($0 , /\/\*/); # 查找/*位置

if(notes1 > 0 && notes21 == 0) { # //注释
stat = 1;
}
if(notes1 == 0 && notes21 == 0) #无注释
stat = 0;

if(notes1 >0 && notes21 >0) {
if(notes1 < notes21)
stat = 1;
else
stat = 2;
}

if(notes1 == 0 && notes21 > 0)
stat = 2;

if(stat == 1) { # 此时为//注释
stat = 0;
num_notes += 1;
next;
}
if(stat == 2){ 	# /*注释
notes22 = match($0 , /\*\//);
if(notes22 == 0) { #没找到*/
num_notes += 1;
next;
}
if(notes21 < notes22) { # /**/注释一行
num_notes += 1;
stat = 0;
next;
} else {
print "error , find */ before /*\n"
exit;
}
}
}

if(stat == 2) {
num_notes += 1;
if($0~/\*\//) {
stat = 0;
}
}
}

END {
print num_notes;
}


如果你非要用shell的话,那你写个shell调用吧,最简单的方法

#!/bin/sh

./get-cfile-notes.awk $1

就行了

试验:

#include <stdio.h>

/* this is my first program */
// haha

int main()
{
/* this is my first program
thank you !
*/

printf("hello world!\n"); //printf statement
return 0; /* return *? */
}
将其保存为main.c

然后./get-cfile-notes.awk main.c

输出:

7
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: