2017-09-05 114 views
1

我需要在linux下使用sed删除C程序中的注释行,假设每个注释行包含开始和结束标记,而前后没有任何其他语句。SED删除C程序注释

例如,下面的代码:

/* a comment line in a C program */ 
printf("It is /* NOT a comment line */\n"); 
x = 5; /* This is an assignment, not a comment line */ 
[TAB][SPACE] /* another empty comment line here */ 
/* another weird line, but not a comment line */ y = 0; 

成为

printf("It is /* NOT a comment line */\n"); 
x = 5; /* This is an assignment, not a comment line */ 
/* another weird line, but not a comment line */ y = 0; 

我知道,这正则表达式

^\s?\/\*.*\*\/$ 

,我需要删除线相匹配。但是,下面的命令:

sed -i -e 's/^\s?\/\*.*\*\/$//g' filename 

没有办法。

我不太确定我在做什么错...

感谢您的帮助。

+0

您应该在您的示例中包含'/ *第一条评论* /非评论/ *第二条评论* /',因为sed脚本难以正确处理。你现有的答案都不能正确处理,他们都认为这是一条评论线。 –

+0

https://unix.stackexchange.com/questions/297346/how-can-i-delete-all-characters-falling-under-including – bishop

回答

2

该做的:

$ sed -e '/^\s*\/\*.*\*\/$/d' file 
printf("It is /* NOT a comment line */\n"); 
x = 5; /* This is an assignment, not a comment line */ 
/* another weird line, but not a comment line */ y = 0; 

注:

  1. ^\s?匹配零个或一个空格。看起来你想匹配零个或一个或多个空间。所以,我们使用^\s*

  2. 由于您要删除行而不是用空行替换它们,因此要使用的命令是d进行删除。

  3. 没有必要用/分隔正则表达式。我们可以用|,例如:

    sed -e '\|^\s*/\*.*\*/$|d' file 
    

    这样就不必为了躲避/。根据/在正则表达式中出现的次数,这可能会也可能不会更简单和更清晰。

0

你在做什么与空字符串

sed -i -e 's/^\s?\/\*.*\*\/$//g' filename 

这意味着

sed -i -'s/pattern_to_find/replacement/g' : g means the whole file. 

你需要做的更换您的正则表达式是删除该行与正则表达式

sed -i -e '/^\s?\/\*.*\*\/$/d' filename 
1

这可能是你l ooking为:

$ awk '{o=$0; gsub(/\*\//,"\n"); gsub(/\/\*[^\n]*\n/,"")} NF{print o}' file 
printf("It is /* NOT a comment line */\n"); 
x = 5; /* This is an assignment, not a comment line */ 
/* another weird line, but not a comment line */ y = 0; 
/* first comment */ non comment /* second comment */ 

以上在此输入文件运行:

$ cat file 
/* a comment line in a C program */ 
printf("It is /* NOT a comment line */\n"); 
x = 5; /* This is an assignment, not a comment line */ 
    /* another empty comment line here */ 
/* another weird line, but not a comment line */ y = 0; 
/* first comment */ non comment /* second comment */ 

,并使用awk的,因为一旦你过了一个简单的S /老/新/万物容易(和更有效,更便携等)与awk。以上将删除任何空行 - 如果这是一个问题,然后更新您的示例输入/输出,以包括它,但这是一个简单的修复。