删除C代码注释的脚本

sh/bash/dash/ksh/zsh等Shell脚本
回复
头像
alinmn
帖子: 185
注册时间: 2006-05-19 21:42
来自: NIT

删除C代码注释的脚本

#1

帖子 alinmn » 2008-11-21 20:15

为了便于统计代码行数,写了个去掉代码注释的脚本,perl的。

代码: 全选

#!/bin/perl -w
#Remove comments in c/c++ source file
#Usage: removecomment.pl Infile [Outfile]

use strict;


if(@ARGV < 1)
{
	print STDERR "removecomment.pl Infile [Outfile]\n";
	exit;
}

my ($infile,$outfile) = @ARGV;

open (FI,"$infile") || die "Can not open file:$!";
my @lines = <FI>;
close (FI);

my $contents = join '',@lines;

$contents =~ s/((?<=\n)|^)[ \t]*\/\*.*?\*\/\n?|\/\*.*?\*\/|((?<=\n)|^)[ \t]*\/\/[^\n]*\n|\/\/[^\n]*//gs;

if(!(defined($outfile)))
{
	print $contents;
}
else
{
	open (FO,">$outfile") || die "Can not open file:$!";
	print FO $contents;
	close (FO);
}
顺便问一下,正则表达式怎么表达向前的“懒惰”的匹配,比如“aaaxxxb”中,我想匹配最短的"a.*b",即“axxxb”,"a.*?b"还是会把整个都匹配到,这里a可以理解为一个模式,不然我用"a[^a]*b"就可以了。
头像
bearscafe
帖子: 694
注册时间: 2007-05-05 23:11

Re: 删除C代码注释的脚本

#2

帖子 bearscafe » 2008-11-29 9:58

alinmn 写了:顺便问一下,正则表达式怎么表达向前的“懒惰”的匹配,比如“aaaxxxb”中,我想匹配最短的"a.*b",即“axxxb”,"a.*?b"还是会把整个都匹配到,这里a可以理解为一个模式,不然我用"a[^a]*b"就可以了。
这样行不行:匹配

代码: 全选

a.*(a.*b)
,然后取$1
头像
alinmn
帖子: 185
注册时间: 2006-05-19 21:42
来自: NIT

Re: 删除C代码注释的脚本

#3

帖子 alinmn » 2008-11-29 16:38

:em01 是可以的 不过要稍微改一下 (a.*)?(a.*b)
头像
bearscafe
帖子: 694
注册时间: 2007-05-05 23:11

Re: 删除C代码注释的脚本

#4

帖子 bearscafe » 2008-11-29 19:36

alinmn 写了::em01 是可以的 不过要稍微改一下 (a.*)?(a.*b)
哦对,有道理。
另外第一个括号应该用非提取型的,要不$1的内容不定。
回复