Saturday, December 21, 2013

Vim - How to add contents of external file to current buffer

This will insert the contents of test.txt into the buffer directly below the cursor:

:r ~/test.txt

r = Read contents

This will replace the buffer with the contents of test.txt:

:%!cat ~/test.txt

Breaking the above command down:

% = Entire contents of buffer
! = Run an external command
cat = Concatenate (display)
~ = Home directory
test.txt = Filename

The ! (bang) command lets us run external programs from the shell.  Of particular interest, we can run commands against the Vim buffer.  For example, the command below will run a shell sort command against the contents of the Vim buffer:

:%!sort %

The first % is necessary because it tells Vim we are about to do something to the entire contents of the buffer.  Everything after the !bang is the external command.

Another (silly) example - this runs the word count (wc) command:

:%!wc %
:%!wc

More realistic examples would use various external commands to chop up the contents of the Vim buffer - commands such as cut, sed, and so on.

Note to self:  There is a subtle difference here between appending the second "%" symbol in the first command and leaving it out in the second command.  This needs further investigation.

---

Shout out to my buddy Mark Moser for sending me a one-liner and making me remember/research this!  His one liner follows.

:r! cal 2014







No comments:

Post a Comment

Note: Only a member of this blog may post a comment.