7.2. 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:


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


The time and date will appear on your screen; press RETURN 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:


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 ...

Get Learning the vi Editor, Sixth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.