【问题标题】:removing the comment line from text file从文本文件中删除注释行
【发布时间】:2018-09-19 05:31:21
【问题描述】:

我有一个包含以下文本的文本文件。

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

【问题讨论】:

  • 跨多行的 cmets 怎么样?
  • 先去掉空格和制表符,替换文件。
  • ???替换文件?这是什么意思?

标签: linux shell unix command


【解决方案1】:

您可以使用此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 */

【讨论】:

    【解决方案2】:

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

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

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

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

    grep  '^/\*.*\*/$' small.txt
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-02
      • 2015-05-11
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      相关资源
      最近更新 更多