Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

1 Answer 1

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.

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

Your Answer

 
discard

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.