1

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;
Tomas Greif
  • 21,685
  • 23
  • 106
  • 155
  • 1
    Not exactly related, but you may be interested in this answer from the [Stack Overflow Regular Expression FAQ](http://stackoverflow.com/a/22944075/2736496), listed under "Advanced Regex-Fu": [Get a string between two curly braces: `{...}`](http://stackoverflow.com/questions/413071/regex-to-get-string-between-curly-braces-i-want-whats-between-the-curly-brace). – aliteralmind Apr 10 '14 at 15:46

1 Answers1

1

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;
devnull
  • 118,548
  • 33
  • 236
  • 227