A short guide to the ed editor
By Flavio Copes
A short guide to the ed editor, the original UNIX text editor, covering how to enter write mode with a, save the buffer to a file, print content and quit.
ed is the original UNIX text editor, and it’s the most basic you can work with. It’s also very rarely used, if ever used, by most people.
ed is a line editor. There is no cursor and no visible text on screen. You type commands, and each command works on one or more lines of the file.
That sounds strange today, but it made sense in 1969, when the output device was a printer. And it’s why vi (and later Vim) feel the way they do: their command language descends directly from ed.
How do you write and save a file?
Run it by typing ed. This starts an interactive session. You get no prompt at all, just a blinking cursor. That’s normal.
Enter in write mode by typing a on a single line, and press enter. Then type everything you want, and once you are done, write just a dot (.) on a line and press enter.
Now type w followed by a file name to save the buffer to a file. It will return the number of bytes written to the file.
You can then press q to quit.
Here is a full session that creates a two-line file:
ed
a
milk
bread
.
w shopping.txt
11
q
The 11 is ed telling you it wrote 11 bytes.
Editing an existing file
You can edit a file with ed by invoking it with the file name: ed shopping.txt. It prints the file size in bytes, and nothing else. When you press a to add, you add content to the bottom of the file.
Inside an ed session you can type ,p to print the current file content. The comma means “every line”. Use ,n instead to print with line numbers.
Commands accept line addresses. 1p prints the first line, $p prints the last one, 2d deletes line two.
s/milk/oat milk/ replaces text on the current line, with the same syntax sed and Vim use.
Where’s the error message?
When ed doesn’t understand you, it answers with a single ?. That’s the entire error message.
Type h right after and it explains what went wrong.
One pitfall gets everyone at least once: typing commands while you’re still in input mode. After a, everything you type is text, including w and q, until you enter the lone dot. If your “commands” are being ignored, type . on its own line first, then run them.
If you want a visible prompt, start the editor with ed -p '*' and every command line shows a *.
To leave without saving, q warns you once with a ?. Type q again, or use Q to quit unconditionally.
Related posts about cli: