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

今天看到一求助帖子再问这个事,所以无聊写了个。

用的是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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值