A macro like @Nobe4's may be the easiest, but you could also do a substitution. It can be tricky to express the substitution since you want it to be 'global' within the quoted string, but not really global for the line (i.e., replace all whitespace, but only for the first quoted string on the line). One way is to do a non-global substitution to replace the whole first quoted string, and for replacement use an expression which makes a global substitution on that string from ' ' to '_'.
:%s/'[^']*'/\=substitute(submatch(0), ' ', '_', 'g')/
or
:%s/'.\{-}'/\=substitute(submatch(0), ' ', '_', 'g')/
Maybe this feels a little clunky compared to a macro, but it can be a useful technique sometimes.
Details
:
- enter cmdline mode
%
- for all lines in buffer
s
- substitute (the three /
characters delimit the substitute command, see :help :substitute
)
'.\{-}'
or '[^']*'
- regex that matches anything surrounded by single quotes
\=
- substitute with an expression (see :help sub-replace-expression
)
substitute()
- the expression is a call to :help substitute()
submatch(0)
- the entire matched string is retrieved with submatch(0)
and is the first argument to substitute()
' ', '_'
- the substitution on the string
'g'
- global flag, i.e., substitute all occurrences
If we had ended the :substitute
command with a global flag (/g
) then it would have substituted all occurrences of quoted strings on the line. As it is, it only does the first. In the call to substitute()
however we do use the global flag ('g'
) in order to replace all occurrences of ' '
in the quoted string.