Unix shell script to remove blank lines following opening brackets
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:
/^ *{/
means search for 0 or more blank spaces before the first{
.- Then set a flag to true (
f=1
). - 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 usingnext
. - 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//
精彩评论