Lazer
Lazer

Reputation: 94840

How to perform concatenation of lines based on a condition in vim?

In vim, how can I run the following logic over my file:

If the line n not end with a semicolon, concatenate lines n and n + 1.

I have files which have broken SQL statements:

broken version

select * from tab1;
select col4, col5 from
 tab5;
insert into
 tab6 values(
2, 4);

required version

select * from tab1;
select col4, col5 from tab5;
insert into tab6 values(2, 4);

Upvotes: 2

Views: 468

Answers (2)

Zsolt Botykai
Zsolt Botykai

Reputation: 51613

Shameless "dirty" "hack" ;-)

:1,$ join  

this join every line on the file to a single one, but you can adjust the range...

:s:;:&\r:g 

this replaces every ; with a ; and a newline

HTH

Upvotes: 1

Luc Hermitte
Luc Hermitte

Reputation: 32946

:v/;$/normal J

You may have to run it several times.

EDIT: Here is a solution that solves lines split on multiple (>2) lines:

%s/^\s*$\|\([^;]\)\s*\n/\1/g 

Note: Empty lines are kept, but trimmed, thanks to the ^\s*$

Upvotes: 4

Related Questions