sudoedit.com!

Using the :read command in vim

This post assumes you know enough about vim to use it relatively comfortably. If you have never used it, or only have cautious interactions with it then you'll want to start with a tutorial.

From your terminal type vim then, Esc followed by :vimtutor press Enter and do the full introduction before proceeding.


The famous vim text editor has lots of great features one of the lesser known features (or one I didn't know about till recently anyway) is the read command.

You can use read in command mode to insert the contents of another file, or the output of a command into a vim buffer (file).

Insert the output of a shell command into vim

This site is written in markdown using Hugo. In Hugo each post has some meta data associated with it that is written at the top of each file called front matter.

Front matter tells Hugo things like: the author, title, date, tags, etc of each post. It looks something like this:

---
authors: ["Luke Rawlins"]
date: 2022-05-01
draft: false
title: vim read command
url: /vim-read
tags:
- vim
---

Instead of writing all that each time I wanted to create a new post in vim, I could use the :read command to insert the front matter of a previous post each time I start a new file.

For example if I wanted to insert the front matter from my previous post I could do that like this:

:read !head 2022-04-09-vimwiki-neovim.md

Or you can shorten it up by just using :r

:r !head 2022-04-09-vimwiki-neovim.md

Which in my case inserts this output into my file:

---
authors: ["Luke Rawlins"]
date: 2022-04-09
draft: false
title: How to install vimwiki in neovim
url: /install-vimwiki-neovim
tags:
- vim
- Linux
---

Those 10 lines are the front matter of my last post. But lets take a look at each part of this command string.

One of my most often used cases for inserting the output of a shell command into vim is when I'm building an index file for my notes using the ls command.

:r !ls -C1 /path/to/notes/directory/


Use :read to pull in an entire file.

You might have a need to make a completely new version of a file. Perhaps you want to copy in a configuration file and just make a few minor changes. Or use it to create a template.

:r /path/to/file/

This time instead of getting the output of a shell command you get the contents of another file pulled directly into your current buffer (file).


If you found this useful please support the blog.

Fastmail

I use Fastmail to host my email for the blog. If you follow the link from this page you'll get a 10% discount and I'll get a little bit of break on my costs as well. It's a win win.


Backblaze

Backblaze is a cloud backup solution for Mac and Windows desktops. I use it on my home computers, and if you sign up using the link on this page you get a free month of service through backblaze, and so do I. If you're looking for a good backup solution give them a try!

Thanks!

Luke