I have some part of a line visually selected. I would like to remove all non-word characters in the selection and replace all whitespace characters with underscores.

How would I go on about this?

link|improve this question

67% accept rate
feedback

1 Answer

up vote 2 down vote accepted

The following assumes a basic familiarity with the Vim :substitute command. First replace the whitespace characters with underscores.

:'<,'>s/\%V\s\%V/_/g

Typing : while text is visually selected will automatically fill in

:'<,'>

The \%V before and after the space cause the enclosed pattern (the space) to match only within a visually-selected region. Next remove the non-word characters. Type gv to re-select the region. Then type

:'<,'>s/\%V\W\%V//g

where \W is a Vim regex atom meaning "non-word character." See

:help /\%V
:help /\s
:help /\W
:help gv

Typing the \%V can be awkward. The vis.vim plugin simplifies this by allowing one to execute any ex command on a visually-selected region by typing : then B then the ex command, simplifying the above to

:'<,'>B s/\s/_/g
gv
:'<,'>B s/\W//g

where again, Vim fills in the '<,'> part for you.

Edit
I replaced "space" with "whitespace characters" above after re-reading the question.

link|improve this answer
Great! I didn't know about \%V. – Nickolay Kolev May 20 '11 at 20:19
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.