开发者

Unix shell script to remove blank lines following opening brackets

开发者 https://www.devze.com 2022-12-18 04:10 出处:网络
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. For example,

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. For example,

void func()
{


    foo();
}

void bar(开发者_StackOverflow社区)
{

    helloWorld();
}

should become

void func()
{
    foo();
}

void bar()
{
    helloWorld();
}

Any thoughts?


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 there is no fields, i.e., the line is blank), skip line using next.
  4. When the next line which is not a blank line (i.e., NF{f=0} means toggle back the flag), the rest of the lines will not be affected until the next opening brace.


Vim:

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


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! :-)


Perhaps the simplest way of doing that in Vim is the following substitution:

:%s/^\s*{\n\zs\_s*\n//
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号