在多行注释块外显示行

Display lines outside multiline comment block

我正在尝试从 Unix 文件中过滤掉多行注释。我们将使用该文件 运行 对抗 Oracle 引擎

我尝试使用下面的方法,但它没有显示我想要的正确输出。

我的文件 file.sql 包含以下内容:

/* This is commented section
asdasd...
asdasdasd...
adasdasd..
sdasd */
I want this line to print
/* Dont want this to print */
/* Dont want this
  to print
  */
Want this to 
  print
    /*
Do not want 
this to print
*/

我的输出需要如下所示::

I want this line to print
Want this to 
  print

我尝试使用下面的 perl 来首先显示多行注释中的行,但它没有显示正确的输出:(

perl -ne 'print if //*/../*//' file.sql

我的主要目标是不显示多行注释行,只显示前面提到的输出。

试试这个:

perl -0777 -pe's{/\*.*?\*/}{}sg' file.sql

输出:

I want this line to print


Want this to 
  print

解释:

  • -0777 : 吸食模式
  • 修饰符标志s:使点匹配新行
  • 修饰符标志g:全局重复匹配模式

你们非常亲密。这似乎可以满足您的要求。

#!/usr/bin/perl

use strict;
use warnings;

while (<DATA>) {
  print unless m[/\*] .. m[\*/];
}

__DATA__
/* This is commented section
asdasd...
asdasdasd...
adasdasd..
sdasd */
I want this line to print
/* Dont want this to print */
/* Dont want this
  to print
  */
Want this to 
  print
    /*
Do not want 
this to print
*/

输出:

I want this line to print
Want this to 
  print

问题出在触发器两端使用的两个匹配运算符 (//*/../*//)。

首先,如果您使用斜杠作为匹配运算符的分隔符,则需要对正则表达式中的任何斜杠进行转义。我通过从斜杠 (/ ... /) 切换到使用 m[ ... ] 来解决这个问题。

其次,* 在正则表达式中有特殊含义(它表示 "zero or more of the previous thing")所以你需要转义它们。

所以我们最终得到 m[/\*] .. m[\*/]

哦,你需要颠倒你的逻辑。你在使用 if 而它应该是 unless.

正在转换为您使用过的命令行脚本:

perl -ne 'print unless m[/\*] .. m[\*/]' file.sql