Suppose I want to edit a new libvirt XML file:

virsh dumpxml machine1 > machine2.xml

Then I open the file with vim,

vim machine2.xml

and then I want to change the UUID. Now do this, I use

:r ! uuidgen

But the new UUID is inserted under the current line:


How may I insert the output of the uuidgen command into the current line, so that if I have


(with the cursor between ><), then, by executing uuidgen I get


The question is: is possible to use the :r vim command without adding a new line?


I had a play around and this doesn't do exactly as you want as :r will always enter a newline. But it should do what you want for a result.

:.!UUID=`uuidgen` ; echo "<uuid>$UUID</uuid>"

It puts the stdout on the current line (not at the cursor) - the smarts are done with the command that is being invoked.

  • It create also a newline, is a nice workaround, so for the moment I consider as right answer – elbarna Mar 25 at 22:47

:read is an Ex command; these unfortunately always work on complete lines. You either have to work around that by first splitting and then later joining with the preceding and following lines, or you use a different command.

The :help i_CTRL-R command can insert any register contents. There's a special expression register (:help quote=) that executes any Vimscript expression and uses its result. Finally, the system() function executes an external command and returns its output.

So (in insert mode) <C-R>=system('uuidgen')<CR> will insert the command's output at the current position. Unfortunately, the output has a trailing newline, and that is preserved, so </uuid> moves to the next line. To avoid that, you can truncate the output, either via system('uuidgen')[0:-2] or substitute(system('uuidgen'), '\n$', '', '') as the expression.

For repeated inserts, the expression history can be used to recall the last expression (by pressing <Up>); for even more comfort, you can define a mapping for the whole thing.

fu! SetBang(v) range
        if a:v == 1
                normal gv
        let l:t = &shellredir
        let &shellredir = ">%s\ 2>/dev/tty"
        let @" = join(systemlist(input("\"!"))," ")
        let &shellredir = l:t
nnoremap "! :cal SetBang(0)<cr>
xnoremap "! :cal SetBang(1)<cr>

Every time you press "!, the user will be prompted for a command, and the "unnamed" " register will be filled with it. You can then insert it as usual, with P in normal or visual mode, with Ctrl-R" in insert mode, etc.

For instance, having the text (caret showed by |):


and pressing "!uuidgen<Enter>P will insert the new uuid at the caret.

You could of course use other binding instead of "!.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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