使用 sed 命令删除多种类型的注释



>我有一个C文件的目录。我想从这些源文件中删除所有类型的评论。

例如,假设我有一个类似于以下文件的源代码。

#include <stdio.h>
int main() {   
int number;
/* Sample Multiline Comment 
* Line 1
* Line 2
*/
printf("Enter an integer: ");  
// reads and stores input
scanf("%d", &number);
printf("You entered: %d", number); //display output 
return 0;
/* Comment */
}

我想删除此代码中的所有类型注释。这包括,

//    
/* */   
/*
*
*/

我尝试使用 sed 命令执行此任务。

find . -type f |xargs sed -i 's,/**,,g;s,*/,,g;s,/*,,g;s,//,,g'

这只会删除上述注释符号本身,而不会删除注释。我想删除整个评论以及上述三个评论符号。

我怎样才能达到这个标准。

从两个角度来解决这个问题。

  1. 删除以匹配条件开头的行
  2. 您可以删除以某些条件开头并以不同条件结尾的内容。

删除以条件开头的行:

sed '/^/// d'

要在开始和结束之间删除使用:

sed 's//*.**/://'

警告。 当您有其他行可能以适用字符开头时,请小心。

我希望这就是你要找的。

这是一种对awk的尝试,但也许它有帮助:

#! /usr/bin/env bash    
awk '
function remove_comments(line)
{
# multi-line comment is active, clear everything
if (flag_c == 1) {
if (sub(/.*[*][/]$/, "", line)) {
flag_c=0
}
else {
# skip this line
# its all comment
return 1
}
}
# remove multi-line comments(/**/) made on the same line
gsub(/[/][*].*[*][/]/, "", line)
# remove single line comments if any
sub(/[/][/].*$/, "", line)
# make flag_c=1 if a multi-line comment has been started
if (sub(/[/][*].*/, "", line))
{
flag_c=1
}
return line
}
##
#   MAIN
##
{
$0 = remove_comments($0)
if ($0 == 1 || $0 == "")
next
print
}
' file.c

为此,最好使用 C 预处理器,如从 C/C++ 代码中删除注释的答案所示。

您可以要求预处理器通过运行gcc -fpreprocessed -dD -E foo.c来删除注释。

$ cat foo.c
#include <stdio.h>
int main() {
int number;
/* Sample Multiline Comment
* Line 1
* Line 2
*/
printf("Enter an integer: ");
// reads and stores input
scanf("%d", &number);
printf("You entered: %d", number); //display output
return 0;
/* Comment */
}
$ gcc -fpreprocessed -dD -E foo.c
# 1 "foo.c"
#include <stdio.h>
int main() {
int number;


printf("Enter an integer: ");

scanf("%d", &number);
printf("You entered: %d", number);
return 0;
}

最新更新