- 论坛徽章:
- 0
|
1. /* aaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbb
ccccccccccccccccccccccccc */
2. /* ddddddddddddddddddddddddd */
3. int foo; /* eeeeeeeeeeeeeeeee */
4. /* ffffffffffffffff */ int bar;
5. int foobar; /* gggggggggggggggg
hhhhhhhhhhhhhhhh
iiiiiiiiiiiiiiii */
方法1:
# 定义一个变量del,用于表示目前是否处于跨行注释的处理过程中,初值为0
BEGIN { del = 0 }
# 如果当前行中含有/*...*/,则将这部分删除,这是第2、3、4种注释形式
/\/\*.*\*\// { sub(/\/\*.*\*\//, "") }
# 如果当前行中还含有/*,则可能是第1、5种注释形式。先将del设为1,并将当前行
# 自/*至行尾的内容删除,若此时当前行中还有除空格之外的其它字符,则说明当前
# 行属于第5种形式的第一行,需要输出,否则属于第1中形式的第一行,属删除之列,
# 此处不必做任何处理
/\/\*/ { del = 1; sub(/\/\*.*$/, ""); if (!match($0, /^ *$/)) print }
# 如果当前行中还含有*/,则说明当前行是第1、5种形式的最后一行,此行属删除之
# 列,不输出。将del清0,表示本段跨行注释处理完毕。直接读入下一行
/\*\// { del = 0; next }
# 如果当前行中现在只剩下若干空格了,表示当前行或者本来就是空行,或者是在前面
# 的处理中变成空行的,都在删除之列,不输出。直接读入下一行
/^ *$/ { next }
# del等于0,表示目前不在跨行注释处理过程中,当前行原样输出
del == 0 { print }方法2:
一个现成的例子 from man lex
CODE:
[Copy to clipboard]
/* file name comm.l */
%{
#include
#include
%}
%%
"/*" {
register int c;
for ( ; ; )
{
while ( (c = input()) != '*' &&
c != EOF )
; /* eat up text of comment */
if ( c == '*' )
{
while ( (c = input()) == '*' )
;
if ( c == '/' )
break; /* found the end */
}
if ( c == EOF )
{
printf( "EOF in comment" );
exit(0);
break;
}
}
}
%%
$lex comm.l
$gcc -o erase lex.yy.c -lfl
$./erase text.plain.c
方法3:
初试perl,也来一个。。。
CODE:
[Copy to clipboard]
#!/usr/bin/perl -w
# move C/C++ source file all comment
# CopyError(R) windwiny. #### NO ANY WARRANTY ####
#
# Usage:
# mvcommen.pl bbb.c
#
$cc1=0; # line comment and \ ended;
$cc2=0; # block comment begin but no end blocked.
while ()
{
# aaa // bbb ccc \
# ddd eee \
# fff
if ($cc1 !=0)
{
if (m/(.*)(\\$)/)
{
next;
}
else
{
$cc1=0;
next;
}
}
if (s/(.*?)(\/\/.*)(\\$)/$1/)
{
print ;
$cc1=1;
next;
}
# aaa // bbb ccc // ddd /* eee */ ... except above 's case
s/(.*?)(\/\/.*$)/$1/; # NOT next
# aaa /* bbb ccc
# ddd eee
# fff */ ggg
if ($cc2 !=0)
{
# ? WARRING: disable /* /* */ */'s style comment
if (s/(.*?)(\*\/)(.*)/$3/)
{
print ;
$cc2=0;
next;
}
next;
}
# aaa /* bbb */ ccc
if (s/(.*?)(\/\*.*?\*\/)(.*)/$1$3/)
{
print ;
next;
}
# --> join up #### CAN NOT move above 's if above ####
if (s/(.*?)(\/\*.*$)/$1/)
{
print ;
$cc2=1;
next;
}
# Other case:
# aaa /* bbb
# ccc */ ddd; /* eee */ or // fff
# This is too BT,can not moved. :-(
# default
print;
}
# vim:ts=4:sts=4:sw=4:cin
方法4:
awk脚本:
CODE:
[Copy to clipboard]
BEGIN { del = 0 }
/\/\*.*\*\// { sub(/\/\*.*\*\//, "") }
/\/\*/ { del = 1; sub(/\/\*.*$/, ""); if (!match($0, /^ *$/)) print }
/\*\// { del = 0; next }
/^ *$/ { next }
del == 0 { print
方法5:
sed
CODE:
[Copy to clipboard]
sed -n 'H;${g;s#/\*[^*]*\*/##g;s/\n *\n//g;p}' foo.c方法6:
lex
CODE:
[Copy to clipboard]
%{
%}
comment "/*"([^\*]|(\*)*[^\*/])*(\*)*"*/"
%%
{comment} { }
%%
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/22837/showart_190379.html |
|