robert
robert

Reputation: 8717

Changing non-hanging braces to hanging braces

What is the regex to change

class ABC
{
}

to

class ABC {
}

I can use J command for one line,but how to do this for entire file.

Thanks

Upvotes: 1

Views: 375

Answers (5)

nelstrom
nelstrom

Reputation: 19562

A few of the answers suggest using a substitution command. To me, it feels more appropriate to use a :global command in combination with the :join command. Start by creating a suitable search pattern:

/\n{

This works for the simple example given in the question, but it may need to be refined depending on the contents of the file that you are working on. Once you've got your search pattern, you can run the global command:

:g//j

If you leave the search field blank, Vim automatically uses the last search pattern (this is also true for the :substitute command). I prefer breaking the global command into two separate steps, but you could just as well do it in a one-er. Here is the long-hand form:

:g/\n{/join

Upvotes: 4

johnny
johnny

Reputation: 657

For your example this worked for me on gVim: %s /class.*\zs\_[^{]*{/ {\r/

Upvotes: 0

YXD
YXD

Reputation: 32521

Try the following:

:%s/\(class.*\)\_.{/\1\ {/g

(updated)

Upvotes: 0

Fredrik Pihl
Fredrik Pihl

Reputation: 45670

How about recording a macro, i.e.

/class               # search for class
gg                   # goto beginning of file
qq                   # start recording of macro
J                    # join lines
n                    # move to next match
q                    # stop recording

execute using @q

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96306

Use the following search and replace:

:%s/\n{/ {/g

Upvotes: 0

Related Questions