Executing Unix Commands

You can display or read in the results of any Unix command while you are editing in vi. An exclamation mark (!) tells ex to create a shell and to regard what follows as a Unix command:

:!command

So if you are editing and you want to check the time or date without exiting vi, you can enter:

:!date

The time and date will appear on your screen; press ENTER to continue editing at the same place in your file.

If you want to give several Unix commands in a row without returning to vi editing in between, you can create a shell with the ex command:

:sh

When you want to exit the shell and return to vi, press CTRL-D.

You can combine :read with a call to Unix, to read the results of a Unix command into your file. As a very simple example:

:r !date

will read in the system’s date information into the text of your file. By preceding the :r command with a line address, you can read the result of the command in at any desired point in your file. By default, it will appear after the current line.

Suppose you are editing a file and want to read in four phone numbers from a file called phone, but in alphabetical order. phone reads:

Willing, Sue  333-4444
Walsh, Linda  555-6666
Quercia, Valerie  777-8888
Dougherty, Nancy  999-0000

The command:

:r !sort phone

reads in the contents of phone after they have been passed through the sort filter:

Dougherty, Nancy  999-0000
Quercia, Valerie  777-8888
Walsh, Linda  555-6666
Willing, Sue  333-4444

Suppose you are editing a file and want to insert text ...

Get Learning the vi and Vim Editors, 7th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.