从文本文件中删除注释行

问题描述 投票:1回答:2

我有一个文本文件,里面有以下文字。

/* 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;

我想用/*删除带有开头的行,并仅使用linux命令以*/结束。

我编写了以下代码来执行此操作。

egrep "^/*.+*/$" small.txt

我将文本保存在我的small.txt文件中。

但它输出所有仅以*/结尾的行。

输出如下。

/* a comment line in a C program */
 x = 5; /* This is an assignment, not a comment line */
 [TAB][SPACE] /* another empty comment line here */

我想要的输出是

/* a comment line in a C program */
linux shell unix command
2个回答
3
投票

您可以使用此sed删除注释行:

sed '\~^/\*.*\*/$~d' file.c

或者使用grep

grep -v '^/\*.*\*/$' file.c

 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;

要仅打印匹配的行:

sed '\~^/\*.*\*/$~!d' file.c

或使用grep

grep '^/\*.*\*/$' file.c

/* a comment line in a C program */

0
投票

首先,我们将删除空格和制表符,如下所示。

sed "s/^[ \t]*//" -i small.txt

这将替换small.txt与删除前导空格和制表符的那个。

我们将运行以下命令来提取注释。

grep  '^/\*.*\*/$' small.txt
© www.soinside.com 2019 - 2024. All rights reserved.