【问题标题】:Display lines outside multiline comment block在多行注释块外显示行
【发布时间】:2019-12-19 20:43:39
【问题描述】:

我正在尝试从 Unix 文件中过滤掉多行 cmets。我们将使用该文件针对 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 text-processing


    【解决方案1】:

    你们很亲密。这似乎可以满足您的需求。

    #!/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[ ... ] 来解决这个问题。

    其次,* 在正则表达式中具有特殊含义(它的意思是“之前的零个或多个”),因此您需要转义这些。

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

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

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

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

    【讨论】:

      【解决方案2】:

      试试这个:

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

      输出

      I want this line to print
      
      
      Want this to 
        print
      

      解释

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

      【讨论】:

      • 完全适合我和要求。你太棒了。
      猜你喜欢
      • 2014-01-15
      • 1970-01-01
      • 2012-05-15
      • 2021-11-16
      • 2019-10-30
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      相关资源
      最近更新 更多