16. Directories And Files
Introduction to FreeBSD
16.1.  Reading the Manual Pages
16.2.  The File System
16.3.  Viewing Text Files *
16.4.  Moving Files Around
16.5.  Managing Permissions *
16.6.  Text Editing in System Administration: vi

Start in Late July.

16.1.   Reading the Manual Pages

The FreeBSD manual pages (or manpages as they are usually called) describe nearly every user command, administrative command, library call, and file format used on the system, plus some other informative tidbits (like a built-in ASCII table). Each page includes a summary, lists all the options available with the command, and generally goes into detail about the command and refers you to related pages.

Man page information is only available on actual commands, not to aliases you set up in your .cshrc file.

To access the Manual Pages, type in man command at the Unix Command Prompt with out the quotes. Substitute the word ``command'' with the command that you are interested in learning about. For Example:

/usr/home/chris> man ls

The above command will generate a manual page explaining the use ofls. While you are viewing the man page, you can control the screen the same way you would control a more session.

Pressing these keys will result in the following:

  • "q" Will quit the current man session.

  • "b" Causes Man to go back to the previous screen.

  • "j" Causes Man to go forward one line.

  • "k" Causes Man to go back one line.>

  • "<SPACE>" Causes Man to go forward one page.


In order to access the online man pages, you must have the man distribution installed on your system.

man searches all the directories specified in the MANPATH environment variable to find the page you requested.

You can adjust the MANPATH search string to include custom man page directories so you can add your own man pages. Man Pages are divided up in to Nine sections. The first of these contains all of the user commands.

Almost every install option in the FreeBSD sysinstall includes the manual pages. So unless you have selected the custom install and didn't choose the man pages, you should have access to them on your system

16.2.   The File System

When you are new to UNIX, especially when converting from a non-UNIX operating system like DOS or MacOS, figuring out which commands do what you want can be very frustrating. Most of the help features built in to UNIX are designed to help you figure out how to fully use a command AFTER you have discovered it.

One of the first commands that you have to learn is ls ls is a command to ``list'' or display all of the files that are present in your current path. In order to comprehend all the things that ls can show us, we need to first understand how UNIX treats files.

There four main types of files:

  • Regular files

  • Directories

  • Devices and Special files

  • Linked files

Regular files include programs, data files, pictures, binary executables, etc... These account for almost all of the files that will exist on your system.

Directories are files that allow you to contain other files in them. On windows and the Mac systems they are called "folders." All regular files are contained inside a directory. Directories can be contained in side of other directories, these are called sub-directories. Dos users will notice that the directory separator in UNIX is the opposite direction from that in DOS. For more information on directories see the man pages on pwd cd mkdir and rmdir

Devices are accessed through special files that are contained in the /dev directory. These files allow you to control various parts of the computer, such as your modem or floppy disk. Device drivers access these files to give instructions to things like your mouse or sound card.

Also reference the man pages for: MAKEDEV, mknod, and

Link files are a lot like pointers in C. Links come in two types: real links and symbolic links. Real links are actually another name for the file. A real link has a few limitations, it can't be linked to a directory and it must exist on the same physical disk and disk partition. However symbolic links, or symlinks as some people call them, don't have this limitation. A link to a file allows you to move the file from it's original place, and still allow programs that depend on it to find it. A Symlink can be thought of as a shortcut to a file. ``Shortcuts'' in Win95 work exactly the same way. Deleting the symlink doesn't delete the actual file, just the shortcut to it. For more information on links, see the man page for ln

Every file has certain properties. These consist of:

X|Kind of File|
v|Read Write|X|Number of Links|
v|Execute |v| | | | | |time| |
v|permission|v|Owner| Group | Size |month|day|year|File Name|
crw-rw-rw- 1 root wheel 	2, 12 Aug 28 1996 zero
brw-r----- 1 root operator 0, 7 Aug 28 1996 wd0h
brw-r----- 1 root operator 0, 146 Aug 28 1996 wd0s3
brw-r----- 1 root operator 0, 682 Aug 28 1996 wd0s4
-r-xr-xr-x 1 bin bin 	45056 Feb 28 04:05 cat
-r-xr-xr-x 1 bin bin 	53248 Feb 28 04:05 chmod
-rw-rw-r-- 1 chrisc bsdbook 416 Mar 24 23:09 .cshrc
-rw-rw-r-- 1 chrisc bsdbook 420 Mar 24 23:09 .login
-rw-rw-r-- 1 chrisc bsdbook 0 Mar 10 13:38 help
drwx------ 2 chrisc bsdbook 512 Apr 3 01:46 mail
drwxrwxr-x 5 chrisc bsdbook 512 Mar 24 23:22 public_html
lrwxr-xr-x 1 root wheel 	 11 Mar 23 22:56 sys -> usr/src/sys

Files that begin with a ``.'' are hidden files, and are not usually displayed by ls and by default they are not acted upon by most other programs.

There are two special files that exist in every directory: . and .. these refer to the ``current'' and ``previous'' directories respectively.

16.3.   Viewing Text Files *

16.3.1.  CAT:
16.3.2.  MORE:
16.3.3.  TAIL:
16.3.4.  HEAD:

Most of the work you do as a system administrator involves text files. Either you are checking a config file, or viewing a log file. To accomplish the job of displaying text files, Unix provides several different tools.

16.3.1.   CAT:

cat is short for concatenate. If you don't redirect it elsewhere, cat will display a file to the standard output, namely the monitor you are looking at. cat displays the file as fast as possible, and will not stop for page breaks. For Example:

cat myfile

will display the contents of ``myfile'' to the screen. However, if that file happens to be a non-text file, such as a binary file, you would see all of the binary escape codes; it might not be a pretty sight.

If more than one filename is specified, cat will display them one after the other, in order, without pausing, as though they were one file. By using the redirection operator > you can concatenate two or more files together and create a third file that contains all the information from the other files.

For example:

cat file1 file2 file3 > file4

In this example, file4 would contain all the information from files 1,2, and 3. It would not matter if this was a text file or a binary file, because the information would never be shown to the screen.

16.3.2.   MORE:

But what if while we are using cat we have a file that is too long to fit on one screen, and we really want to read what it says as it scrolls past us at sub-light speed. Over the years people have come up with several programs to make the display pause for page breaks and let us read the page before showing us a new one. One of the first and more popular ways is more Two other commands, less and page have recently become popular. Currently, less is just a hacked version of more Fundamentally more works just like cat except more pauses for page breaks and prompts you to press a key before it continues. However, it isn't always easy to tell which key to press, because it doesn't tell you. It just sits there with a ``stdin'' in the lower left hand corner. It assumes that we have read the man page, and know that ``stdin'' stands for ``standard input device'' ie. the Keyboard. It is waiting for us to press the SPACE BAR to go one page forward, the ENTER key to go one line forward, b to go back a page, or q to quit out of it.

By using the pipe operator | we can route all the information through more and make any program that is displaying text to the screen slow down and pause at page breaks. For example, a ls -lR / will display all the files in our computer. This would be very hard to read, and we wouldn't get much out of it. But if we do a ls -lR / | more this will show us the directory listings one page at a time and also allow us to stop by pressing q

16.3.3.   TAIL:

Sometimes, however, we have a real long file and we are only concerned with the last page of information. It would be silly to use cat or more and wait all the way through 1500 pages of text just to see the last page. Log files are a prime example of a situation like this. For example, you are checking the log for the web server and you want to see who the last few visitors are, or you want to check the last couple of messages in /var/log/messages. In situations like these, it is a good idea to use tail.

If we wanted to see the last messages in /var/log/messages, type:

tail /var/log/messages

The last page of the message file will be displayed on your screen.

16.3.4.   HEAD:

head works just like tail except it show only the first page full.

Also reference the man pages for: more less head page tail cat

For more information on these commands, see the man pages for: more, less, head, page, tail, and cat

16.4.   Moving Files Around

Files, they seem to be everywhere; in FreeBSD this is very true. Except they never seem to be where you want them. There are basically three things that you can do with files: Create them, Use them, and Remove them. The rest of the time is spent moving them around from place to place in your file system. To move files around in a file system, you have to have places to move them to and from. These places are called directories. Directories are really files that contain other files. Files can be placed inside a directory and moved from one directory to another.

Directories can be placed inside each other. A directory contained inside of another directory is called a ``sub-directory''.

To move a file or directory, we need to use the mv. mv requires that you have at least to parameters when moving files. (Some people call these ``arguments''.)

The first parameter is the source file, or the name of the file you want to move. The second parameter is the destination, or the place you want to move the file to. If you specify a directory as the destination, it will place that file in the directory specified. If you give it a file name as the destination, it will rename your file. If you move a directory using mv, it will rename the directory.

For Example:

mv /usr/local/junk.html /usr/local/www/ mv /usr/local/html /usr/local/www mv /usr/local/junk.html /usr/local/www/index.html mv /usr/local/junk.html /usr/local/www/ mv junk.html junk.htm mv /usr/local/html/* /usr/local/www/

16.5.   Managing Permissions *

Security is a big issue in today's ``anyone-can-access-your-site'' Internet environment. For the new-to UNIX user and even system administrator, keeping access permissions set properly on files can be a major chore.

Permissions to a file allow a user to read, write, or execute a particular file based on whether he is the owner of the file, a member of the group that owns the file, or an ordinary user that is trying to use the file. UNIX lets you set the accessibility permissions for each of the three categories. Individual file permissions are set with the command chmod. The command umask is used to set the default permissions that a file gets when it is created. chmod and umask use a number and column scheme to represent the particular permissions and the category that they apply to.

There are four columns and four numbers (if you count zero). The columns represent the categories that the permissions apply to and the numbers are the read and write permissions.

The Columns:

	|column1 | column2 | column3 | column4|
	|Special | Owner | Group | Others |

The Numbers:
	In Column 1 only: 4 |Set User ID On Execution.
			 2 |Set Group ID On Execution.
			 1 |Set the Sticky Bit.
			 0 |Remove all Special options

	In Columns 2-4	 4 |Grant Read Permissions
			 2 |Grant Write Permissions
			 1 |Grant Execute Permissions
			 0 |Remove all permissions from column

If you specify less than four digits when setting permissions it will assume that you are starting from column 4 and work backwards, in other words chmod 22 file will set the read permissions of file to ``write'' for group and others. chmod 24 file and chmod 0024 file are exactly the same. This however will remove all permissions from the user, a better one to use would be chmod 644 file for standard files and chmod 755 file for executable files. You can have no more than 4 digits, each corresponding to a column.

You can set both read and write permissions to a column by adding the numbers together. Write(2) + Read(4) = Both Read and Write(6). Therefore to set read and write permissions to ``Owner'', ``Group'', and ``Others''; you would use chmod 666 file

The file ``bsd.gif'' has been set to mode 664 using the command chmod 664 bsd.gif

An ls -l will display the permissions of all the files in the current directory.

>ls -l

total 21
drwxr-xr-x 2 chrisc bsdbook 512 Mar 21 00:50 articles
-rw-rw-r-- 1 chrisc bsdbook 926 Mar 21 16:01 blueball.gif
-rw-r--r-- 1 chrisc bsdbook 1901 Mar 21 23:50 book.html
-rw-rw-r-- 1 chrisc bsdbook 7100 Mar 21 15:57 botbar_raw.gif
-rw-rw-r-- 1 chrisc bsdbook 2088 Mar 21 15:57 bsd.gif
drwxrwxr-x 3 chrisc bsdbook 512 Mar 22 00:02 cgi-bin
drwxrwxr-x 2 chrisc bsdbook 2560 Mar 21 15:50 docs
-rw-rw-r-- 1 chrisc bsdbook 0 Mar 22 00:15 file
-rw-rw-r-- 1 chrisc bsdbook 2865 Mar 21 15:47 umask.sgml
^^^^^^^^^^ These are the permissions.

The 'd' tells us which files are directories. Directories must have execute permissions enabled in order for a user to change directories to it. A '-' in the first field signifies an ordinary file, in the other fields it signifies a lack of permissions, or a permissions of '0'.

When a file is created the default permissions are set at 666. Umask does just the opposite job of chmod. It removes permissions from the default values at creation time based on the number and column scheme. Therefore to have your files set to read and write by ``Owner'', but read only by ``Group'' and ``Others'', you would use a umask of 22. The Line

umask 22

can be put in your .login file and automatically set every time you login.

	The Default Permissions: 	666
	Your Umask Values:		 22
	Your New Default Permissions: 644

Now every time you create a file it will have the New Default permissions. A umask of 66 would give you Default permissions of 600, giving only the owner read and write access to the file. chmod can also modify permissions to files using a ``first letter'' short notation. This style of using chmod works exactly the same as the Column and Number Scheme. However, it is easier for new users to remember and use. Consequently it gets a lot of use in everyday tasks, while the Column and Number Scheme gets a lot of use by programs and scripting languages.

	Permissions Types:
		r	Read
		w	Write
		x	Execute

	Affected Area: (column)
		u	User
		g	Group
		o	Others
		a	All

	Method Affected:
		+	Add to
		- 	Remove from
		=	Set equal to

To add execute permissions to all areas of the file ``bsd.gif'', you would use chmod a+x bsd.gif

To remove read permissions from ``Others'' use chmod o-r bsd.gif.

Now you can control the initial permissions of files and modify those permissions later to suit your needs.

16.6.   Text Editing in System Administration: vi

16.6.3.  Cut N Paste:
16.6.4.  Special:
16.6.5.  EX MODE or ``:'' COMMANDS:
16.6.6.  Numbers:

In FreeBSD there are several text editors available; one of the most powerful and common is vi. However, to people who haven't grown up using it, learning vi may appear to be the hardest part of System Administration. Used properly, vi is one of the best tools for System Administration. When learning vi the first thing that must be understood is that vi is not a word processor. It is a text editor designed to edit the configuration files that are used by the system; at this job it excels and is (in my opinion) easy to use.

The biggest problem is that vi doesn't even pretend to be user-friendly. If you don't know how to use it, there is absolutely nothing to tell you which key to press to accomplish the required task. Generally, all it does is beep at you. To the advanced user, the lack of help menus is a "feature" not a draw-back, because the screen is not cluttered with unused help features.

Because of the lack of help features in vi, and the difficulties most people have learning it, other text editors have been created. One of those is vim, or ``vi improved''. vim has taken all of the functionality of vi and made it easier to use.

A program named pico from the University of Washington, is a very easy to use text editor. It provides a lot of help features and opens automatically into ``text entry mode''. FreeBSD now ships with the ee editor as the Default. It is very easy to use, but cluttered with help screens.

Unlike most other editors, vi has three modes: Command Mode, Text Entry Mode and EX mode. In Command Mode, each key you press is part of a command. Cursor movement, deleting lines, searching, and such are done in command mode. When you start vi, it starts you out in Command Mode and you have to Enter the correct keys to get to Data Entry Mode.

From Data Entry Mode you can enter text just as you would in a normal text editor. There are several commands to start Text Entry Mode, revolving around what you want to happen prior to entering the text. You will remain in Text Entry Mode until you press the ESC key, which will return you to Command Mode. To start a new document, type vi from the command line followed by the name of the file you wish to create. This will put you into a clean document, provided you have not named an already existing file, and start you off in Command Mode. Now any key entered will be interpreted as a command and vi will promptly beep at you if you press the wrong one. At this point press a to begin entering text. Now enter in several lines of text; if you don't press return, vi will treat this all as one line, with no word wrapping. This is an important feature of vi in System Administration. Some configuration files require that certain lines all be entered on one line.

vi will also show you all the escape characters contained in the text. This is a very helpful feature if you are working with special file formats. Editors like pico will often not display special characters. They will sometimes even remove them.


Press the ESC key to return to Command mode. Use the h and l keys to move the cursor left and right. In vi all the commands are case sensitive. The following commands will move the cursor in various ways.

h One Space Left.

l One Space right.

j One Line Down.

k One Line UP.

w Forward/Right One Word.

b Back/Left One Word.

G Goto Bottom of Document.

Many of the other commands can be combined with these motion commands.

16.6.2.   TEXT ENTRY MODE:

Now position your Cursor at the end of a word and press a. The cursor moved one space forward and is allowing you to append text after that word. Press the ESC key and return to Command Mode. Position your cursor at the end of the same word. This time press i and type some characters. The letters were inserted in front of the cursor position. The following command will allow you to enter Text Entry Mode in various ways.

a Append after the cursor position.

A Append at the End of the Line.

i Insert before the cursor position.

I Append at the Beginning of the Line.

o Open a new line Below the cursor.

O Open a new line Above the cursor.

16.6.3.   Cut N Paste:

y Copies or "Yanks" a line *

d Deletes *

c Changes *

p Pastes Below Cursor

P Pastes Above Cursor

* Note:

These need to be mixed with motion commands to make these effective. Pressing the same key affects the current line. (ie. yy yank current line)

Position your cursor on a line with text on it and press dd This will delete the current line and save it to a temporary buffer. you can restore it by pressing p.

16.6.4.   Special:

/ Search

n Find the next match.

. Repeat last Command

u Undo/Redo

The search, repeat, and ``find next'' commands allow you to do a search-and-replace in a very controlled manner. For example, you have a document that has the word me in it several times. You want to change it to the word ``you'' To do this you would search for ``me'' by typing /me. Your cursor will jump to the nearest word containing me. Then type cwyou and press the ESC key. This will change the word to you. Now you are set up to search for and replace all the other ``me'' words in the document. To find the next occurance of ``me'' press n to change it to ``you'' press .; if you don't want to change it, press n to go on to the next.

/me will match any word containing me, words like: reames,mess, and mean. Use /\ me\ to find only the word me.

16.6.5.   EX MODE or ``:'' COMMANDS:

w < filename > Write the file

q Quit vi

w! < filename > Over Write an existing file/force write

q! Quit without saving/force quit

r < filename > read in a file

!ls execute the shell command ls

123 goto line 123

When you press the : key, a : will appear in the lower left hand corner of the screen. This is a prompt that will accept a limited number of commands. It will let you execute shell commands, read in files, or quit vi. When you are done with vi, press :wq and you will save your file and quit out of vi.

To read in or write to a file, you need to supply a file name. If you supplied a file name when starting vi, it will use it by default. Giving a filename at this point would override the one you supplied at startup.

16.6.6.   Numbers:

In command mode, if you enter a number, it will repeat the next command that many times. For example, if you are deleting lines, typing 10dd will delete 10 lines. Motion commands may be used also; 10dk will delete 11 lines above and including the one the cursor is on.


16.7.1.  Introduction
16.7.2.  (Part I/a) An explanation of the syntax of vi commands.
16.7.3.  (Part I/b)Quick help and covers some of the important(in my mind) vi
16.7.4.  (Part I/c) a listing of all the vi commands and their function.
16.7.5.  (part II/a) The syntax of how addresses work in ex. commands
16.7.6.  (part II/b)A quick list of almost all of ex commands and their abbreviations.
16.7.7.  (Part II/c) A listing of almost all of the standard ex commands and their function.
16.7.8.  (part III)A quick explanation of regular expressions as they are used in vi/ex.

In-depth help for learning the vi editor.

16.7.1.   Introduction

vi has basically three modes,
1) command or normal mode,
2) insert or input or append mode
3) ex or command-line mode.
vi starts in command mode where you can issue commands, move and/or
cut/copy text. The : (colon) puts you in ex mode where you can use powerful
ex commands like g, s, v, ! etc. certain commands will put you in insert
mode, eg. i, I, a, A, o, O. When in insert mode you can type in text. R
will put you in a special case of insert mode, that is overwrite mode ^[
(escape key) will put you in command mode.

16.7.2.   (Part I/a) An explanation of the syntax of vi commands.


most commands in vi have the following form ( exceptions are : m, M, n, N,
p, P, u, U )
[n] operator
5x delete 5 characters
3ANO! will insert NO! three times at the end of the line if you hit ESC
 after typing the !
2fa forward to second a on line
3Tc backward to after the third c
20j move cursor down 20 lines
5H move cursor 5 lines from top of screen
5rx replace next 5 characters with x
5$ move to end of 5th line down (line 1 is current)
3_ move to first non-blank character 3 lines up (line 1 is current)
editing commands(c,d,y,>,<,!) have the following general form
[n] operator [m] object
an object in vi would be a character or a word or a line or a sentence etc.
basic operators for editing are
c begin a change
d begin a delete
y begin a yank
if the current line is the object of the operator then the object is the
same as the operator: cc, dd, yy.
if both n an m are specified the effect is n * m, that is n times m.
cw change word
c2W change next two WORDS (includes punctuation) (could also be 2cW)
2cc change two lines
c$ change to end of line
c) change to end of sentence
5dd delete next five lines
d5G delete to line 5
dG delete to end of file
de delete to end of word
d^ delete to beginning of line
d30| delete to column 30 on line
yy yank current line
y'z yank to line marked with z
y]] yank up to next section
yL yank to bottom of screen
y2fq yank to second q on line forward

commands in vi are not echoed to the screen except the following:
/ search forward for pattern
? search backward for pattern
: invoke an ex command
! invoke a unix (OS) command that takes as its input an object in the
 buffer and replaces it with output from the command
 eg. 1G!Gsort -fd
the above commands are completed by pressing the return key
a buffer in vi would refer to the file as it's kept in memory

<, >, and ! can also be combined with a movement command like c, d, and y
>> indent current line one shiftwidth
5<< outdent 5 lines starting with current
>>% indent to matching parentheses
!Gsort -fd sort from current line to end of file

16.7.3.   (Part I/b)Quick help and covers some of the important(in my mind) vi

QUICK HELP ( commands and command combinations to get you statrted in vi )

h cursor left
j cursor down
k cursor up
l cursor right
space cursor right

[n]G to line n
0, $ first, last position on line
+, - first character on next, previous line
^, _ first character on current line (other than tab or space)

^F, ^B scroll forward, backward one screen
^D, ^U scroll forward, backward half screen
^E, ^Y show one more line at bottom, top of screen

Marking position:
mx mark current position with x
`x move cursor to mark x
'x move cursor to first non-whitespace character containing mark x

Miscellaneous movement:
fa forward to character a
Fd backward to character d
tg forward to character before g
Tw backward to character after w
w beginning of next word
W beginning of next WORD (punctuation is part of word)
b back one word
B back one WORD (punctuation is part of word)
e end of word
E end of WORD (punctuation is part of word)
zENTER position line with cursor at top of screen
z. position line with cursor at middle of screen
z- position line with cursor at bottom of screen
), ( next, previous sentence
]], [[ next, previous section
}, { next, previous paragraph
( the above will depend on your settings for what constitutes a "section"
and "paragraph" )

Inserting text:
a append after cursor
A append at end of line (same as $a)
i insert before cursor
I insert at beginning of line (same as _i)
o open line below cursor
O open line above cursor
^[ terminate insert mode (escape)

Deleting and changing text:
cw change word
C change line starting with current character (same as c$)
cc change current line
2cc change 2 lines
dH delete to top of screen
dd delete current line
dj delete current line and one below it
d/pat delete to pat(tern)
d`z delete to character marked with z
d'z delete to line marked with z
de delete to end of word
d% delete to matching bracket
P put text previously yanked or deleted before/above cursor
p put text previously yanked or deleted after/below cursor
4s substitute 4 characters
S substitute entire line
u undo last change
. repeat last change
~ reverse case
11~ reverse case of next 11 characters (on current line)

Copying and moving:
yy copy current line to (unnamed) buffer
"xyy copy current line to buffer x
"xp put contents of buffer x below cursor
ye yank to end of word
"xyG yank from current line to end of file into buffer x
y2k yank current line and two above it
y'x yank to line with mark x
y`x yank to character with mark x
3>> indent next three lines one shiftwidth
>>34G indent current line to line 34 one shiftwidth

Save and exit:
:x quit vi, write file if changes were made
:w file save copy to file
:w >> file append copy to file
:q! quit vi, do not save changes
:e! return to file before changes were made, after last write
:e# edit alternate file

Interacting with OS:
:!command run command
:r file read in contents of file after cursor
:r !command read in output of command after cursor
:n,m! command run command on lines in file from n to m and replace with output
!object command send buffer object to command, replace with output (eg.
 !G sort -fd will sort from the current line to end of file)
ncommand send n lines to command, replace with output

16.7.4.   (Part I/c) a listing of all the vi commands and their function.


( ^A stands for control-a ^i stands for 
-i )

a append after cursor (can be preceded by a number)
A append at end of line (same as $a) (can be preceded by a number)
^A unused
b back up one word (can be preceded by a number)
B back up one WORD (including punctuation) (can be preceded by a number)
^B scroll up one screen (can be preceded by a number)
c begin a change (combine with movement command) 
 (can be preceded by a number)
C change line from cursor to end of line (same as c$) 
 (can be preceded by a number)
^C unused; in insert > end insert mode
d begin a delete (combine with movement command) 
 (can be preceded by a number)
D delete from cursor to end of line (same as d$)
 (can be preceded by a number)
^D scroll down a half screen (can be preceded by a number); 
 in insert > back up on shiftwidth
e goto end of word (can be preceded by a number)
E goto end of WORD (including punctuation) (can be preceded by a number)
^E show one more line at bottom of screen (can be preceded by a number)
f forward to next typed character (can be preceded by a number)
F backward to next typed character (can be preceded by a number)
^F scroll down one screen (can be preceded by a number)
g unused
G goto specified line or end of file (can be preceded by a number)
^G print file info on status line (bottom of screen)
h cursor left (can be preceded by a number)
H goto top of screen (can be preceded by a number)
^H left cursor; in insert > backspace
i insert before cursor (can be preceded by a number)
I insert at beginning of line (same as _i)
 (can be preceded by a number)
^I unused; in insert > tab key
j cursor down (can be preceded by a number)
J join two lines (can be preceded by a number)
^J down arrow cursor key; in insert > same as enter
k cursor up (can be preceded by a number)
K unused
^K unused
l cursor right (can be preceded by a number)
L goto bottom of screen (can be preceded by a number)
^L redraw screen usually
m mark current cursor position with character typed (a-z)
M goto middle of screen
^M to beginning of next line (can be preceded by a number);
 in insert > same as enter key
n repeat last search command
N repeat last search command in reverse direction
^N down arrow cursor key
o open a new line below the cursor (can be preceded by a number)
O open a new line above the cursor (can be preceded by a number)
^O unused
p put yanked or deleted text after or below cursor
P put yanked or deleted text before or above cursor
^P up arrow cursor key
q unused
Q quit vi, invoke ex (not very useful) return with vi
^Q unused (some terminals, stop data flow)
r change character under cursor to character typed 
 (can be preceded by a number)
R replace characters (overwrite mode) (can be preceded by a number)
^R redraw screen usually
s substitute characters under cursor to ones typed 
 (can be preceded by a number)
S change entire line (can be preceded by a number)
^S unused (on some terminals, resume data flow)
t forward to before next character typed (can be preceded by a number)
T backward to after next character typed (can be preceded by a number)
^T goto previous tag; in insert > move right one shiftwidth
u undo last change
U restore current line
^U scroll screen up a half screen (can be preceded by a number);
 in insert > delete back to start of insert (depends on terminal
v unused
V unused
^V unused; in insert > quote next character
w forward one word (can be preceded by a number) 
W forward one WORD (including punctuation) (can be preceded by a number)
^W unused; in insert > back up to beginning of word (depends on
 terminal settings)
x delete character under cursor (can be preceded by a number)
X delete back one character (can be preceded by a number)
^X unused
y begin a yank (combine with movement command) 
 (can be preceded by a number)
Y yank current line (same as yy) (map it to y$ to be consistent with
 D and C) (can be preceded by a number)
^Y show one more line at top of screen (can be preceded by a number)
zENTER reposition line with cursor to top of screen
z. reposition line with cursor to middle of screen
z- reposition line with cursor to bottom of screen
 (the three z commands above can be preceded by a number)
ZZ quit vi, write file if changes were made
^Z suspend vi on systems that have job control (depends on terminal

^@ unused
^[ terminate insert mode (escape key)
^\ I don't think it does anything
^] goto tag under cursor
^^ edit alternate file
^_ unused?
^? unused? delete key?

space cursor right (can be preceded by a number)
! filter program through external filter, requires an object to work on
 (combine with movement command) (press enter to execute)
" use register for next delete, yank or put, registers are (a-zA-Z0-9)
# unused?
$ goto end of line (can be preceded by a number)
% goto matching bracket () [] {}
& repeat last substitute
' to first non-blank character on line with mark (a-z)
( beginning of next sentence
) beginning of current sentence (sentence is delimited by ., !, ? and
 followed by at least one space)
* unused
+ down one line to first non-blank character (j_)
 (can be preceded by a number)
, repeat f, F, t, T commands in reverse direction
- up one line to first non-blank character (k_) 
 (can be preceded by a number)
. repeat previous command
/ search forward for text entered (repeat previous search if no
 argument supplied) (press enter to execute)
0 goto beginning of line
: enter an ex command (press enter to execute)
; repeat f, F, t, T commands
< begin a shift left (combine with movement command) 
 (can be preceded by a number)
= unused (unless in lisp mode in which case it formats to standard
 lisp formatting)
> begin a shift right (combine with movement command) 
 (can be preceded by a number)
? search backward for text entered (repeat previous search backward
 if no argument supplied) (press enter to execute)
@ execute a register (0-9a-z".)
[[ beginning of current section (as delimited by the sect= option)
\ unused
]] beginning of next section (as delimited by the sect= option)
^ goto first non-blank character on line
_ goto first non-blank character on line (can be preceded by a number)
` goto mark (a-z)
{ beginning of current paragraph (as delimited by a blank line or the
 p= option)
n| column n of current line
} beginning of next paragraph (as delimited by a blank line or the
 p= option)
~ change case of character under cursor (can be preceded by a number)

16.7.5.   (part II/a) The syntax of how addresses work in ex. commands

address symbols
0 beginning of file
$ end of file
1,$ all lines in file
% stands for filename, hence it means the entire file (1,$)
# stands for alternate file
x,y lines x through y
x;y lines x through y, current line reset to x
. current line
n absolute line number n
x-n n lines before x
x+n n lines after x
+[n] n lines ahead (default is one)
-[n] n lines back (default is one)
'x line marked with x
'' previous mark
/pattern/ forward to line matching pattern
?pattern? backward to line matching pattern

16.7.6.   (part II/b)A quick list of almost all of ex commands and their abbreviations.

| abbreviate ab | move m | tag ta |
| append a | next n | unabbreviate una |
| args ar | number # nu | undo u |
| change c | open o | unmap unm |
| chdir cd chd | preserve pre | version ve |
| copy t co | print p | visual vi |
| delete d | put pu | write w |
| edit e | quit q | xit x |
| file f | read r | yank ya |
| global g v | recover rec | (window) z |
| insert i | rewind rew | (escape to OS) ! |
| join j | set se | (lshift) < |
| list l | shell sh | (rshift) > |
| map | source so | (line number) = |
| mark k ma | substitute s & ~ | (execute buffer) * @ |

16.7.7.   (Part II/c) A listing of almost all of the standard ex commands and their function.

( anything in [] is optional , anything in {} is the rest of the name of
the command which is also optional )
the default for address is the current line, except for g, g!, v, w; for
these the default is the entire file

ab{breviate} [string text]
 define string when typed to be translated into text.
 if string and text not specified - list all abbreviations
 abbreviations are usually put into your .exrc file
 eg. :ab Xvi vi is the best editor
 :ab character character
 :ab the the
 :ab have have

 append text at address. ! switches autoindent.

 print filename arguments.

cd [path]
 without path change to home directory, with path change to path

 replace lines with text. ! switches autoindent.

 copy lines from address to destination.
 eg. :1,10co50 copy lines 1 to to 10 to below line 50

[address]d{elete} [buffer][count]
 delete lines in address if buffer is specified save lines to buffer.
 count specifies the number of lines to delete starting with address.
 eg. :/include/,/main/d delete lines between include and main
 including include and main
 :/include/+,/main/-d as above but not including include nor main
 :3d delete line 3
 :d3 delete 3 lines starting with current
 :.,$d a delete to end of file from current line into buffer a
 :d a3 delete next three lines starting with current into buffer a

e{dit}[!] [+n] [file]
 begin editing file. ! will discard changes to current file.
 n specifies line to begin editing file (default 1).
 eg. :e file edit file
 :e # edit previous file

f{ile} [filename]
 change name of file to filename. without argument print current
 eg. :f %.new appends .new to current filename, renaming file to

 execute commands on lines that contain pattern, if address is specified
 within the address range. ! execute on lines not containing pattern.
 without commands print matching lines.
 eg. :g/\#include/d delete all lines that have include directives
 :g!/\#define/p print lines that are not define statements
 :g/^\/\*/p print lines that start with /*
 :g/^[ ^I]*$/d delete empty lines as well as lines with only tabs
 or spaces
 :g/strcmp/d5 delete lines that have strcmp in them as well
 as the following 4 lines

 insert text at line before address. ! switches autoindent.

 join lines in specified range. ! preserves white space. 
 eg. :1,5j! join lines 1 to 5, preserve white space

[address]k char
 synonymn for mark, character can follow k with no intervening space.

 print lines so that tabs show as ^I and end of lines are marked with $.

map[!] [char commands]
 define a keyboard macro for named char that is a synonymn for commands.
 ! will create a mapping for input mode. with no arguments print mapped
 eg. :map ^N :n^M (to get a control character type ^V followed by the
 control character)

[address]ma{rk} char
 mark lines with char. char is a single lowercase letter.
 eg. :ma z mark line with z
 :'z return to line with mark z

[address]m{ove} destination
 move lines specified by address to destination.
 eg. :.,/include/m /string/ move lines from current to include line below
 line with string

n{ext}[!] [[+commands] filelist]
 edit next file from argument list. if filelist is provided, replace
 argument list with filelist. ! will discard changes to current file.

 print lines specified by address, precede each line by its line number.
 count specifies the number of lines to print.

 enter vi's open mode with lines specified by address, or at lines
 containing pattern.

 save current buffer as if the system had crashed

 print lines specified by address. count is the number of lines to print.
 eg. :304;+5p print five lines starting with 100, reset current line to

[address]pu{t} [buffer]
 restore lines that were previously deleted or yanked and put them after
 current line. put line from buffer if specified.

 quit. ! discard changes to file.

[address]r{ead} file
 copy text from file on line below specified by address.
 eg. :0r data read in file "data" at top of file

[address]r{ead} !command
 read the output of command into file after line specified by address.
 eg. :$r !ls -aFC run "ls" and read in its output at end of file

rec{over} [file]
 recover file from system save area.

 rewind argument list to first argument. ! discards changes to current

se{t} parm1 parm2
 set value to an option with each parm. if no parm is supplied print all
 changed options. for boolean options parm is phrased as option or
 nooption, other options are option=value. all will print all available
 set commands are usually put into your .exrc
 eg. :se autowrite tabstop=4 autoindent shiftwidth=4 wrapmargin=5
 :se all print all available options

 create a new shell. resume editing when shell exits.

so{urce} file
 read and execute ex commands from file
 eg. so ~/old.exrc

 replace pattern with replacement. if pattern and replacement are omitted
 repeat last substitution. count specifies the number of lines on which to
 substitute starting with address.
 c prompt for confirmation
 g substitute all instances on line
 p print last line on which substitution was made
 eg. :%s/[hH]ello/Hi/g replace hello or Hello with hi, all ocurrences
 :.,$s/[uU][nN][iI][xX]/\U&/10 upcase unix on next 10 lines
 :%s/\<./\u&/g turn the first letter of all words to uppercase
 :1,/main/s/int/long/g substitute occurances of int before main with

[address]t destination
 synonymn for copy

ta{g} tag
 switch to file containing tag.
 eg. :!ctags *.c run ctags on all .c files in directory
 :ta func switch to file containing func, put cursor on it

una{bbreviate} word
 remove word from list of abbreviations.

 undo changes made by last editing command.

unm{ap}[!] char
 remove char from keyboard macros. ! remove macros for input mode.

 synonymn for global!
 eg. :v/./,/./-j join empty lines to have only single empty line
 between lines of text

 version of editor.

[address]vi [type][count]
 enter visual mode at line specified by address. exit with Q. count
 specifies initial window size.
 - place line at bottom of window
 . place line in center of window
 ^ print previous window

vi [+n] file
 begin editing file in visual mode at line n.

[address]w{rite}[!] [[>>] file]
 write lines specified by address to file. >> is used to append to file.
 with no address write all of the file. ! forces the write.
 eg. :1,25w new_file write lines 1 to 25 to "new_file"
 :50,$w >> new_file append line 50 to end of file to new_file

[address]w !command
 write lines specified by address to command.

 write lines specified by address to file and quit. ! forces the write

 exit file. save changes.

[address]ya{nk} [buffer][count]
 place lines specified by address in buffer char. count is the number of
 lines to yank starting with address.
 eg. :20,100ya z yank lines 20 to 100 into buffer z

 print a window of text. count is the number of lines to display starting
 with address.
 + place line at top of window(default)
 - place line at bottom of window
 . place line in center of window
 ^ print previous window
 = place line in center of window. leave line as current line.

 execute command. if address is specified apply lines from address as input
 to command, and replace lines with output.
 eg. :!ls -aFC run ls, will not read output into file
 :0!ls -aFC run ls, read in its output to beginning of file
 :11,35!sort -fd sort lines from 11 to 35
 :%!spell -b run the spellchecker on entire file

 print line number of matching address. with no address print line number
 of last line.

 shitft lines left(<) or right(>). count specifies the number of lines to
 shift starting with address.
 eg. :1,9> indent lines 1 through 9 one shiftwidth

 print line specified by address.

 print next line.

 repeat previous substitution. count specifies the number of lines to
 substitute on starting with address.
 eg. :s/msdos/UNIX substitute msdos with UNIX
 :g/OS/& redo substitutions on all lines with "OS"

 replace previous regular expression with the previous replacement from

 execute named buffer

 synonym for number

The following can be used as addresses in ex, as well as in commands :g,
:s, :v, /, ?

16.7.8.   (part III)A quick explanation of regular expressions as they are used in vi/ex.

. match any single character except newline
* match any number (including none) of the single character immediately
^ match beginning of line if at start of expression
$ match end of line if at end of expression
[ ] match anything enclosed in []
[^ ] match anything not enclosed in []
\( \) store pattern for later replay
\< match following characters at beginning of word 
\> match preceding characters at end of word 
\ escape character following (needed for eg. \. to match a .)
\n reuse previous pattern, n is a number between 1 and 9 eg. \1
& reuse previous search pattern
~ reuse previous replacement pattern
\u change character to upper case
\U change characters to upper case
\l change character to lower case
\L change characters to lower case
\e turn off previous \u or \l
\E turn off previous \U or \L

dig matches dig
^dig matches dig at beginning of line
dig$ matches dig at end of line
^dig$ matches dig as the only word on line
^$ matches the empty line
^..*$ matches a line with at least one character
.* matches any string of characters including none
^[ ^I]*$ as above but line can also contain spaces and/or tabs(^I)
[dD]ig matches dig or Dig
[aA][nN] matches an, aN, An, AN
d[aeiou]g second letter is a vowel
d[^aeiou]g second letter is not a vowel
d.g second letter is anything
^....$ matches a line with exactly four characters
^\. matches any line beginning with a dot
^\.[a-z] same with a lowercase letter following
^[^\.] matches any line that does not begin with a dot
;$ matches a line ending with a semicolon
digs* matches dig, digs, digss, digsss etc.
[a-z][a-z]* matches one or more lowercase letters
[a-zA-Z] matches any character
[^0-9a-zA-Z] matches any symbol (not a letter or number)
\<the matches the, theater, then
the\> matches the, breathe
\< the\> matches the
:%s/\<./\u&/g turn the first letter of all words to uppercase
:%s/\<[a-z][!-~]*\>/\u&/g as above
:%s/\<[a-z]/\u&/g as above
:%s/.*/\L&/ turn entire file to lowercase
:%s/<[^>]*>//g remove strings from file that start with a less than sign
 and end with a greater than sign (html tags)
., ^, &, $ must be preceded by a \ to make literal when magic is on
* must be preceded by a \ under certain circumstances although it never
hurts to precede it with a backslash whenever you mean a * not its regexp
meaning % and # should also be escaped as they mean current and alternate
file to ex

Return to Table of Contents

Visit the Gifcom