2

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
0

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I had no idea about the \zs and \ze things. Very useful. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.