识别多行SQL注释/ * ... * /

时间:2014-04-10 14:19:17

标签: regex replace sed multiline pandoc

我正在尝试使用pandoc将SQL函数源代码转换为html文档。我有一个示例函数:

create or replace function test(a integer, b integer) returns integer as $$

declare
  _c int;
  _d int;

begin

/*Do some basic stuff
----------------------
Do some really basic stuff:

 - this is a list
 - this is a list */

if a = b then
    _c:=a+b;
end if; 

/*Do some more advanced stuff
----------------------------
Description of some advanced stuff */

if a <> b then
    _d:=a*b;
end if;

  return 1;
end;
$$ language plpgsql;

我在评论中使用了markdown。要将整个文件转换为有效的markdown语法,我需要:

  • 在代码为
  • 的每一行的开头添加空格
  • 删除评论标记(/* */

虽然在开头添加空格很容易:

$ sed 's/^/    /' function.sql

同时删除评论标签:

$ sed 's/\/\*//' function.sql
$ sed 's/\*\\//' function.sql

我不知道如何排除评论所在的行。

输出应如下所示:

    create or replace function test(a integer, b integer) returns integer as $$

    declare
      _c int;
      _d int;

    begin

Do some basic stuff
----------------------
Do some really basic stuff:

 - this is a list
 - this is a list

    if a = b then
        _c:=a+b;
    end if; 

Do some more advanced stuff
----------------------------
Description of some advanced stuff

    if a <> b then
        _d:=a*b;
    end if;

      return 1;
    end;
    $$ language plpgsql;

1 个答案:

答案 0 :(得分:1)

使用标签并一次完成所有事情:

sed '/^\/\*/,/\*\//{s|^/\*||; s|\*/$||; b a};s/^/    /;:a' filename

这会缩小除/**/之间的行以外的所有行,并从这些块中删除注释。

为了您的输入,它会产生:

    create or replace function test(a integer, b integer) returns integer as $$

    declare
      _c int;
      _d int;

    begin

Do some basic stuff
----------------------
Do some really basic stuff:

 - this is a list
 - this is a list 

    if a = b then
        _c:=a+b;
    end if; 

Do some more advanced stuff
----------------------------
Description of some advanced stuff 

    if a <> b then
        _d:=a*b;
    end if;

      return 1;
    end;
    $$ language plpgsql;