Let's look at some basic operations using the line editor
ed. Don't worry--this is an exercise intended
to help you learn sed and awk, not an attempt to convince you of the
wonders of line editors. The ed commands that are
shown in this exercise are identical to the sed
commands you'll learn later on. Feel free to experiment with
ed on your own to get a sense of how it works. (If
you're already familiar with ed, feel free to skip
to the next section.)
To use a line editor, you work on one line at a time. It is important
to know what line you are positioned at in the file. When you open a
file using ed, it displays the number of characters
in the file and positions you at the last line.
$ ed test
339
s/regular/complex/g
This command changes all occurrences on the current line. An address
must be specified to direct this command to act upon more than the
current line. The following substitution command specifies an
address:
/regular/s/regular/complex/g
This command affects the first line that matches the address in the
file. Remember, the first "regular" is an address and the second is a
pattern to match for the substitution command. To make it apply to
all lines, use the global command, putting g before the address.
g/regular/s/regular/complex/g
Now the substitution is made everywhere--all occurrences
on all lines.
g/re/p
which stands for "global regular expression print." Grep is a
line-editing command that has been extracted from
ed and made available as an external program. It
is hard-wired to perform one editing command. It takes the regular
expression as an argument on the command line and uses it as the
address of lines to print. Here's an example, looking for lines
matching "box":
$ grep 'box' test
You are given a series of boxes, the first one labeled "A",
label on the first box.
It prints all lines matching the regular expression.
The stream orientation of sed has a major impact on how addressing is
applied. In ed, a command without an address
affects only the current line. Sed goes through the file, a line at a
time, such that each line becomes the current line, and the commands
are applied to it. The result is that sed applies a command without
an address to every line in the file.
Look at the following substitution command:
s/regular/complex/
If you entered this command interactively in ed,
you'd substitute "complex" for the first occurrence of "regular" on
the current line. In an ed script, if this was the
first command in the script, it would be applied only to the last line
of the file (ed's default current line). However,
in a sed script, the same command applies to all lines. That is, sed
commands are implicitly global. In sed, the previous example has the
same result as the following global command in ed:
g/regular/s//complex/