Tutorial 1) Part 7: Editing text files with the Vi editor


Objective: practice typing in insert mode (hit i) and scrolling the cursor in command mode (hit escape and then the hjkl keys).

A simple text editor can be used to modify the text data in an ASCII file. The Vi or Vi IMproved (VIM) editor is commonly bundled with UNIX systems. Terminal editors have a specific set of key commands to learn, but are a powerful tool for programmers. In contrast to graphical user interfaces (GUIs) like MS Word, a terminal text editor can be used while logged on remotely to a multi-user server. A fun introduction to Vi can be found in this Zelda game.

First you will want to download the Vi system settings, or run commands file: Files: my.vimrc

We need to move my.vimrc from your Downloads folder to your Unix home directory:

PC: cd /cygdrive/c/Users tab tab use tab auto-completion after each folder to find the correct path and your username

cd /cygdrive/c/Users/username/Downloads once the path to Downloads is correct hit enter

Mac: cd ~/Downloads

debug1: pwd make sure you moved to the Downloads folder:

/Users/rhills/Downloads


debug2: ls -lrt make sure the file is there and hasn't changed name (-rt shows the most recent files last):

my.vimrc

cp my.vimrc ~/.vimrc rename the file to begin with dot (.), making it a hidden system file in your home directory.

ls -alrt ~ use the -a flag to show all/hidden files in your home


Now download the text file by clicking here: Files: data


Since your terminal is already inside the Downloads directory, it is easy to move it to your home directory:

ls -lrt check that you downloaded the file data (Safari might add .dms to data.dms)


cp data ~/day1 using tab is another way to check that your file data exists, otherwise try to download the file again.

( Safari: cp ~/Downloads/data.dms ~/day1/data )

cd ~/day1 resume the tutorial in your working folder..

ls check that the data file is there.

vim data (you may get a syntax warning: just the hit enter key)

The vim (or vi) command opens an ASCII file in the Vi text editor. By default you can't edit the file: use the following command keys to navigate around the file. Tap the keys (don't hit enter) and observe the result on your screen. The mouse will not move the cursor! The arrow keys should work, but the goal is to get comfortable using hjkl so that we maintain touch typing position at all times. Using Vi is fast once you learn the various commands because your hands never leave the keyboard:

j j j j k k k l l l l h h h G (move cursor)

1G (1 and shift-G in succession goes to line 1)

10G (1-0-G in succession goes to line 10)

$ b b 0 w w w ^f ^f ^b ^b (jump between words)

1G yy j j j p k P 15G 2yy p (yank and paste lines)

G k dd k k k 2dd (delete lines)

1G 10dd u ^r u (undo/redo)

5G w w dw j j j d$ (delete words)

/e enter n n n n n n n j j (pattern searching)

Key: h j k l moves cursor one character at a time (up/down/side-to-side)

G go to line ^f scroll forward ^b page backward

yy yank(copy) lines p/P paste lines dd delete lines u undo ^r redo

b jumps cursor back a word w jumps cursor one word

Now we will type a Vi command by first typing colon and following it with the enter key:

:w my.data enter

:w writes (saves) the file. To quit Vi and return to the Unix prompt type:

:q enter

At the Unix prompt (%), show the file you created:

% ls -lrt

% cat my.data


Let's create a new text file:

% vim notes.txt

One difference you will notice comparing Vi to MS Word is that keystrokes were not inserted as text into the file. This is because you were in command mode--every key executed a command on the file. Another example of commands are system settings. If you didn't download the vimrc into your home directory you can enter these each time you open a file in Vi:

:syntax on <enter> colors programming syntax/comments

:set ruler <enter> shows line and character position of cursor

:set showmode <enter> shows when you leave command mode and can type in insert mode


Try out the following functions in your blank notes.txt file:

  • To switch to insert mode, hit lower-case 'i': you should see -- INSERT -- at the bottom of the screen. Now type a few sentences over the text: try to summarize what we've learned so far. When you're done typing, hit the escape key (or ^c) to go back into command mode. The INSERT display should disappear.

    • Note: for those that don't have an escape key, the .vimrc file maps the <tab> key to the escape function. Control-c may also escape insert mode in Vi. A more general escape to cancel things in your OS is the period key: press command-. (Mac) or ctrl-. (Windows).

  • There are some handy commands for moving the position of the cursor in command mode. Get used to scrolling left/right/up/down with h,l,k,j. Typing 3G moves the cursor to the 3rd line of the file and hitting just capital G goes to the end of file. ^f will page forward and ^b will page backward.

  • Tapping dd will delete a line and entering 2dd will delete 2 lines. Tapping u will undo the last command. Tapping period (.) will redo the last command. Hitting yy copies a line, which you can later paste by holding shift and hitting P. $ moves the cursor to the end of the line. Typing d$ will delete form the cursor to the end of line. Hitting x deletes one character.

  • Capital A inserts cursor at the end of a line, bring you back into insert mode. When you're done entering text, hit escape to go back into command mode.

  • Hitting O or o opens a new line above or below the cursor for editing, respectively, bringing you back into insert mode. Hit escape to go back into command mode.

  • To type over text, hold shift-R to enter replace mode. When you're done, hit escape to return to command mode.

QUESTION 8: Try duplicating some junk text in notes.txt and moving it around using keystroke commands. Which Vi commands do you find to be the most useful?

When finished, save your work by hitting escape to enter command mode and then type the write command :w and hit the enter key:

:wq enter overwrites (updates) the notes.txt file you opened since a new filename isn't given


To illustrate the save function, open the file again from the Unix prompt:

% vim notes.txt

10dd

To force quit without saving the file use an exclamation point:

:q! enter quits without saving current changes

% cat notes.txt

Vi commands are a powerful tool for making repetitive edits to formatted text files, especially if the data is organized into similarly spaced columns, called fields.


We can compress a human-readable text file into a smaller binary file using a zip utility:

ls -lrt

gzip notes.txt

ls

You'll see the file has been appended with the .gz extension and has fewer bytes (column 5 of ls output). We can no longer view it with simple Unix commands:

cat notes.txt.gz

The output is nonsense: Q?)?F?@X?d?e?? .., because the Unix shell is trying to interpret binary data as ASCII text. (The Vi editor is smart enough to work with gzipped files.) Hit the enter key to bring your Unix prompt back.

Later, when you need the text file, it can be unzipped, or decompressed:

gzip -d notes.txt.gz

ls

The gzip utility automatically adds and removes the .gz file extension, so don't have two files with each name in the same directory.

"Piping" the output of one command to another command rather than a file can be useful. Notice how it can feed output to a program that expects input. Mac's have a speech synthesis program say (turn up your volume):

say hello

cat notes.txt | say

A common usage involves piping output that won't fit on the screen into less. For example:

cat notes.txt | less

Hit j or spacebar to scroll down and k to scroll up, similar to Vi. Hit q to quit.

____________________________________________________________________________

Conclusion - Save your work

Save a record of the commands you entered today:

history > ~/day1/history.out


When you close Terminal, files you created will be stored in the folders on your hard drive. To save a record of today's input and output in the terminal, try to select all the text (ctrl-a or command-a) and copy-and-paste it (^c, ^v, etc.) into a Word document or text file (TextEdit.app).


When you no longer need today's terminal(s), you can click to close the windows or type exit:

set savehist=(9999 merge)

exit Typing exit or hitting ctrl-d will close the shell and store your command history in Unix.


As we perform computationally intensive tasks, your computer may start to act slower. Once you've saved your work for today, this may be a good time to completely restart your computer if you haven't in a few weeks:

sudo shutdown -r now

The sudo command allows you to execute special commands as the super-user (require an Administrator password).


We are finished for today! Next, we will be proceeding on to Tutorial 2.