Lots of people here have talked about ed but nobody seems to have explained how to use it. ed is pretty much obsolete cruft nowadays to the extent that knowing how to work the thing is seen as some kind of black magic. But ed is still vaguely useful as a scriptable version of vi. So here is a short introduction (this is not comprehensive; read the ed manpage for full instructions).

The first thing to note about ed is how it deals with errors. ed was designed to be run on teletype printout terminals, so it is very brief in reporting errors (to save ink). If you do something wrong, it prints out "?" but does not say specifically what you did wrong. To find out, use the 'h' command. eg.

?
h
Invalid address

You can invoke ed with a filename to load (ed filename.txt) or to start with an empty file (ed). If you start with an empty file you must first use the 'a' (append) command to enter some text before you can do anything. eg.

a
in ad 2101 war was beginning
what happen?
cant sleep, tustin will eat me!
.

While entering text like this you are in "insert" mode, similar to insert mode in vi. To finish entering text type a line with only a period (".").

While in ed you always have a particular line in the file you are currently at. When you jump to a different line it usually shows the contents of that line. Here are some ways to jump to other lines:

  • Entering the line number: This jumps to particular line in the file. eg. 27 to jump to line 27.
  • $ jumps to the last line in the file. $-1 jumps to the next to last line in the file, $-2 to the second to last, etc.
  • - Jumps to the previous line.
  • + Jumps to the next line. You can also simply type an empty command (hit enter)
  • You can use regular expressions to search within the file. This is also similar to vi: use /regexp/ to search forward and ?regexp? to search backwards.
  • If you lose track of where you are, typing a "." will redisplay the contents of the current line.
Note that the "a" command appends text after your current position. Typing the "i" command inserts text at your current position. This is similar to vi. When starting a new file, you must use the append command to insert new text.

You can perform various operations on the current line, for example use regexps:

.
cant sleep, tustin will eat me!
s/tustin/clown/
.
cant sleep, clown will eat me!

There are various other things you can do to work on lines:

  • d deletes the current line.
  • c goes into insert mode, replacing the current line.
When you are done editing, you can use the w command to write to a file. If you are editing an existing file you can use w on its own to overwrite the old file. w filename.txt will write to a new file named "filename.txt".

q will exit ed. You may have to type it twice if you have a file with unsaved changes.