views:

335

answers:

4

Hi all,

I need a (sed, awk) shell script or, even better, a vim command to remove any blank lines following a line with a single opening curly bracket:

void func()
{


    foo();
}

void bar()
{

    helloWorld();
}

should become:

void func()
{
    foo();
}

void bar()
{
    helloWorld();
}

Any thoughts?

+3  A: 

try this

$ awk 'NF{f=0}/^ *{/{ f=1 } f==1 && !NF{next}1' file
void func()
{
    foo();



}

a bit of explanation:

  1. /^ *{/ means search for 0 or more blank spaces before the first {
  2. then set a flag to true (f=1)
  3. when the next line is read and f is true and !NF (means no fields , ie blank lines), skip line using "next"
  4. When the next line which is not a blank line (ie NF{f=0} means toggle back the flag. ), the rest of the lines will not be affected until the next opening brace
ghostdog74
@ghostdog74: removes the blank lines after opening brackets, but also all other blank lines...
andreas buykx
ok, so you don't want to affect other blank lines.. edited.
ghostdog74
Great, thanks. I'm still trying to figure out, looking at the gawk manpage, how it works though...
andreas buykx
@andreas: I don't think you'll find that last "1" in the man page or the info file.
Dennis Williamson
+2  A: 

Vim:

:%s/^{\(\n\s*\)*/{\r    /g
Alex B
Would add a ^ before the 1st {.
Zsolt Botykai
@Zsolt Botykai: yes, fair point.
Alex B
maybe can be improved to take care of one single { on a line but there are blanks/spaces in front.
ghostdog74
Something like this, I think: `:%s/^\(\s*{\)[\s\n]*/\1\r/`
kejadlen
A: 

The simplest way of doing that in Vim should be something like

:%s/^\s*{\%(\s*\n\)*/{\r/

Note that ^\s*{ matches '{' even if it is not the first non-whitespace character of the line. \%(\s*\n)* matches sequence of empty or whitespace-only lines (it is used \%( here to tell Vim not to store match of the subgroup — it is a bit faster and we don't need this match, actually).

This solution does not use any external tools (so it is possible to use it in Windows, for example). Besides, it is shorter that awk solution mentioned here. ;)

ib
Don't you want `:%s/^\(\s*{\)\%(\s*\n\)*/\1\r/` so that you don't eliminate the spaces in front of the `{`?
kejadlen
A: 

Just for fun, I wanted to figure this out using vim's global command:

:g /{/ s/\n\+/\r/

which is pretty darned short. I hope it works! :-)

jps