awksedmergeksh

Join or merge lines between two patterns inclusive (sed or awk)


I have a large file with multi line SQL statements that I need to "join" into one liners. Consider the following:

create unique index <bla1 bla1>
    <more bla1 bla1>;
alter table <bla2 bla2>
    <more bla2 bla2>;
create index <bla3 bla3>
    <more bla3 bla3>;
alter table <bla4 bla4>
    <more bla4 bla4>
    <some more bla4 bla4>;

in which pattern1 would be "alter table" and pattern2 ";". I would like the output to be:

create unique index <bla1 bla1>
    <more bla1 bla1>;
alter table <bla2 bla2> <more bla2 bla2>;
create index <bla3 bla3>
    <more bla3 bla3>;
alter table <bla4 bla4> <more bla4 bla4> <some more bla4 bla4>;

I've seen other posts about merging lines with sed or awk (closest being sed join lines together, and How to print lines between two patterns, inclusive or exclusive (in sed, AWK or Perl)? kinda gave me a couple of ideas), but they can't quite accomplish the task. While I prefer the answer in sed or awk, any others will be appreciated. Thanks in advance!


Solution

  • Try this:

    sed ':a;/^alter table.*[^;].$/{N;s/\n //;ba}'
    

    EDIT: That's what comes of not having the real tool to experiment with. All right, back to this one:

    sed ':a;/^alter table/{/;$/!{N;s/\n //;ba}}'