Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 3 down vote accepted

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


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


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
:'<,'>B s/\W//g

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

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

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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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