Regex `/pattern/g` and ed `:g/pattern/`: which came first, and why `g`

edhistoryregular expressionsed

The g option (e.g. s/pattern/replacement/g) for many tools that use regex-style pattern matching and the :g command in ed, ex, vi, and vim have pretty similar usage and meaning: match the given regex "globally", i.e., don't stop after the first match.

I have a two-fold question about this:

  • Which came first, the :g command or the g pattern-matching flag, and in which tool? It looks like most tools (such as sed) that use the g flag in their pattern-matching are really just directly or indirectly emulating ed. For instance, in the post-Perl age, most tools that use regex allow the g flag because Perl does, and Perl, it would appear, does it because ed -> sed -> Perl. So I wouldn't be surprised if the answer is "they were introduced simultaneously in the original ed tool, and have no historical precedent beyond that."
  • Why is this called the global option (or command)? There's really nothing "global" about it; the :g command takes a range of lines just like any other ed command, and the g flag doesn't extend the range of the search in any way (it just allows multiple hits). I suppose I can't think of a better name, but the chosen one just seems odd to me, so I'm wondering if there's some reason for it I'm not seeing.

Best Answer

vi is inspired by ex, ex is inspired by ed, ed is inspired by qed

QED was hacked together by Ken Thompson way back in the late 1960's for MIT's "Compatible Time-Sharing System" (a previous version for the Berkeley Timesharing System was created by Butler Lampson, L. Peter Deutsch, and Dana Angluin) — in short Thompson added regex in qed (he did a lot more than that, but it's outside the scope of this answer. -- Bell Labs has more on the history of QED)

One command in qed was the "G" or "Global" command. It allowed you to operate on all lines in the file at once (the previous version of qed were character-oriented instead of line oriented.)

Grep is actually named for one of the uses of this command G/re/P (G global, re regular expression, P print) in qed this command was used like G/bash/P to print out all lines containing the word bash — this was later included in ed, then taken out of ed and made into a standalone function (according to Doug McIlroy, he asked Ken to do it for him & Ken left it on his desk the next morning)

Related Question