views:

264

answers:

3

Given the following line:

[aaaa bbbb cccc dddd] [decimal](18, 0) NULL,

How would you replace the spaces only between the first set of brackets in Vim? What would the /s command look like?

Update:

This is the intend outcome

    [aaaa_bbbb_cccc_dddd] [decimal](18, 0) NULL,
+1  A: 

with the normal setting of 'magic' you'd want to do

:s/] \[/][/

or more fancily

:s/]\zs\s\+\ze\[//

or with the magic level explicitly set in the regex

:s/\V]\zs\s\+\ze[//

\zs and \ze limit the substitution to the area that they enclose.

\M turns off magic completely, so every character or character combo not prefixed with \ is taken literally.

'magic' (:help 'magic') is a global option that determines how potentially-special characters in regexes are interpreted.

intuited
You forgot about look-behind and look-ahead (`s/]\@<=\s\+\[\@=//`).
ZyX
It's `\V` that makes everything other than `\ ` be interpreted literally. `\M` is one step between `\V` and the default setup. Changing the value of `'magic'` is just asking for trouble.
jamessan
intuited
+4  A: 

The easiest way to do it would be to visually select the contents of the []ed string and perform the replacement just on that selection:

vi]:s/\%V \%V/_/g

This doesn't work very well if you're trying to do things programmatically, though. In that case, you can match the entire []ed string and use a replacement expression to construct the result.

:s/\[[^\]]*\]/\=substitute(submatch(0), ' ', '_', 'g')/g
jamessan
McBeth
the =substitute(submatch(0)... was what I needed. Thanks!
Glennular
A: 

You can always go for interactive find and replace, which can be done with flag c

thegeek