Question

I am trying to use pandoc to convert SQL function source code into html documentation. I have an example function:

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;

I am using markdown inside comments. To turn the whole file into valid markdown syntax, I need to:

  • add space at the beginning of every line where the code is
  • remove comment tags (/* */)

While adding spaces at the beginning is easy:

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

And removing comment tags also:

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

I have no idea on how to exclude lines where comments are.

Output should look like:

    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;
Was it helpful?

Solution

Make use of a label and do everything in one go:

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

This would indent all lines except those including and between /* and */ and remove the comments from those blocks.

For your input, it'd produce:

    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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top