:s/\<word1\>/new_word/g

But you need to know the word you want to substitute, if I set it to <cword> and <cword> appears more than once in the line, multiple words will get replaced.

Well, there are several scenarios, each of which vim can handle with aplomb.

If you know the word, but aren't over it, you'll have to type it as above.

If you know the word and the cursor happens to be on it, you can use the control+W register to insert the word currently under the cursor into the command line, so you'd do something like

        :s/\<^R^W\>/new_word/

(that ^R^W is control+R followed by control+W)

If you don't know the word, and just want the first arbitrary word on the line, you can use

        :%s/\<\w\+\>/new_word/

The "g" option toggles whether only the first match gets replaced (no "g" provided), or whether all matches on the line get replaced (the "g" is provided).

If you are only doing one replacement, it's often easier to use the normal-mode

        ciw

command to "change [the] inner word" (or

        ciW

to change the inner "WORD" which is whitespace delimited, rather than punctuation delimited)

and then just type the replacement word. This does have the advantage that if you want to do such replacements in the future, you can just use the period key in normal mode to repeat the replacement in another location.

If you really do mean "<cword>" as for use in certain things like mappings or plugins, you can use something like

        :exec ':s/\<'.expand('<cword>').'/newword/g'

Just a few ideas. The limitation is certainly not vim's...perhaps a more detailed description of what you're trying to do, how often, which instances on a line, and with better definition of what you mean by "word", would help provide a better answer. Hopefully some of the above has been helpful though. My guess, from what I've gathered from your description so far is that either the "ciw" or the ^R^W method are what you're looking for.

For more reading in the help, I recommend

        :help word
        :help WORD
        :help \w
        :help text-objects
                (particularly the "iw", "iW", "aw" and "aW" bits)
        :help 'iskeyword'
        :help c_CTRL-R_CTRL-W
        :help expand()
        :help <cword>

-tim




Reply via email to