Editing Files

We've studied lots of ways to manipulate files, but not very many ways for creating them. For now we will focus on the creation and editing of text files; while the majority of the data on a modern computer is not text, the majority of the files likely are.

Output redirection

Your shell has the ability to redirect command output into a file (overwriting it!) using the syntax COMMAND \> FILE:

# print "hi", then prompt
$ echo hi
hi
$ 

# print "hi" but into a file
$ echo hi > testfile
$ ls testfile
testfile
$ cat testfile
hi
$ echo bye > testfile
$ cat testfile
bye
$ 

If you use two angle brackets, COMMAND \>\> FILE, the file will be appended to:

$ echo hi > testfile
$ echo bye >> testfile
$ cat testfile
hi
bye

The cat command, without arguments, simply takes user input and duplicates it (type Control+D to end input):

# type after hitting [ENTER]
$ cat
the first copy is me typing
the first copy is me typing
the second copy is produced by "cat"
the second copy is produced by "cat"
[CTRL-D]
$ 

You can use this to make multi-line files without typing echo for each line:

$ cat > my-poem
There once was a man from Nantucket.
He liked to live in a bucket.
I don't remember the rest.
[CTRL-D]
$ cat my-poem 
There once was a man from Nantucket.
He liked to live in a bucket.
I don't remember the rest.
$ 

Editors

There are a number of programs to help with editing files.

ed

ed is the standard editor. Be careful about using ed. I don't use ed. (I sort-of know how.) If you accidentally use ed, type q<RETURN> to exit.

nano

The nano editor is considered to be very user-friendly; it is our first example of a terminal, but not command-line, interface. Such systems became popular when screens and synchronous interfaces became practical.

You start nano by running nano [file]. The commands nano responds to are all of the form "Control+"; they are displayed ^<KEY>. For example, ^X Exit means "press Control+X to exit". You use the arrow keys to navigate.

emacs and vim

More sophisticated editors are emacs, a highly extensible modeless editor written in a variant of LISP, and vim, a highly extensible modal editor. I don't really use emacs, but there is a lot of material available online.

vim is a modal text editor; here "modal" means that vim has different interaction paradigms ("modes"). The default mode is called "normal", and each button pressed is interpreted as part of a command. Among several others, normal mode has a simple grammar which can allow you to express otherwise complex ideas very elegantly.

Exercise: read the vim normal mode grammar.

vim also has a reasonably sophisticated plugin system; for example, my web browser and mail client are plugins for vim. vim can be used for spreadsheets, pdf creation, website authoring, programming in most languages, etc. Plugins can also extend vocabularies with new verbs, nouns, and prepositions.