Scalability Blog

Scaling tips, insights, updates, culture, and more from our Server Experts.
 

The Joy of ex

Fellow nerds!  If there’s anything that has a tendency to work up linux guys, it’s text editors.  And in general, people tend to traditionally gravitate towards two camps: camp emacs or camp vi.   While other newer software exists, such as nano, pico, or joe – it’s important to be comfortable using vi and emacs.  vi will be available pretty much everywhere you need it, and emacs, when installed, is intensely featureful.   Besides, using these two editors are a bit of right of passage — you don’t want to look like a nano-using weakling the rest of your life, do you?  (ducks)

Your humble narrator is a vim user, and so we’ll take a look at a few relics from the past that are still used day to day.

Bill Joy (co-founder of Sun) wrote vi over 30 years ago, and us system administrators have been self-flagellating with it ever since.  Prior to vi, people at that time were editing files with a command called ed.  Working with ed must have been an exercise in frustration – it was meant for use on dumb terminals, so in order to modify files you had to work line by line, like this:

[root@xen2 ~]# echo 'line 1
> line 2
> line 3' > file
[root@xen2 ~]# ed file
21
2
line 2
2d
2i
oh god help me
.
2
oh god help me
w
29
q
[root@xen2 ~]# cat file
line 1
oh god help me
line 3
[root@xen2 ~]#

Now just imagine editing a sendmail configuration like that without wanting to rip your eyes out.

Mr. Joy wrote an improved version of ed called, ex.  From there, he continued to build on it so it was able to use the terminal in such a way that it was a visual editor instead of a line editor.  And thus vi came to be.

Those line editor roots are still present in vi, and actually can provide great shortcuts.   For instance in command mode:
Easy search and replace of string1 for string2

:%s/string1/string2/

Remove all lines that just contain whitespace:

:g/^\s*$/d

Occasionally with files from a windows box, there might be some stray line-feed characters in the file.  You can easily remove them with:

:%s/^M//

Note: The ^M in the command actually is inputed: Ctrl-V Ctrl-M

To explain what’s happening in these commands, the initial colon begins the ex command.  Then the % stands for all lines in the file.  If you wanted to specify certain lines, you could express it like:  :1s/string1/string2/
Translated, that’s “Computer!  Please substitute string1 for string2 on line 1″.  Things that are in the first front slashes are regular expressions – meant for matching strings.  Learning and utilizing regular expressions are a key skill that makes life so much easier when utilized properly.

As arcane as some of this can be, it really is worth the effort to learn it.  These shortcuts will save you time over your career at the CLI, and it’s very likely that vi is not going anywhere anytime soon.