使用shell指令碼統計源碼檔案中的注釋行數.(// , /**/)

來源:互聯網
上載者:User

今天看到一求助文章再問這個事,所以無聊寫了個。

用的是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.10BEGIN {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;elsestat = 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 statementreturn 0; /* return *? */}
將其儲存為main.c

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

輸出:

7




相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.