johanrex
johanrex

Reputation: 419

VIM replace in part of pattern

I would like to replace spaces with underscores inside quotes in part of a pattern.

Example input:

select 
    "AA" as "Long descriptive name",
    "BB" as "Another long name",
    "CC" as "There are many spaces here"
from 
    sometable;

Wanted output:

select 
    "AA" as "Long_descriptive_name",
    "BB" as "Another_long_name",
    "CC" as "There_are_many_spaces_here"
from 
    sometable;

I have tried doing this with the substitute() and submatch() functions like this but I can't get it to quite work (The \= part is not interpreted the substitute command is written into the file). Something is missing.

:%s/ as "\(.*\)"/ as \=substitute(submatch(1),' ', '_', 'g')/g

Upvotes: 2

Views: 482

Answers (1)

B.G.
B.G.

Reputation: 6016

well you were close:

:%s/ as "\zs\(.*\)\ze"/\=substitute(submatch(1),' ', '_', 'g')/g

\= only is interpreted as expression if the string starts with it. see :h sub-replace-special. You can solve that problem by just matching the part you want to replace (using \zs and \ze in my example).

This does of course not always work. Then you will have to build a string again in the \= part. Which would look like that:

:%s/ as "\(.*\)"/\=' as "'.substitute(submatch(1),' ', '_', 'g').'"'/g

Upvotes: 2

Related Questions