0

What would the syntax be for replacing only the second/third occurrence of a word/phrase in ed?

He wanted to buy groceries from the shop, but preferred not having to go into the shop. >>
He wanted to buy groceries from the shop, but preferred not having to go into it. >>
Edman
  • 492
  • Why not use sed? – sseLtaH Jun 03 '22 at 05:56
  • 2
    @HatLess ed is an interactive editor, while sed is a non-interactive stream editor based on ed. If one is editing a document in ed, it makes little sense to employ sed for specific actions. – Kusalananda Jun 03 '22 at 06:03

1 Answers1

3

The substitution command in ed, s///, takes zero or more flags at the end of the command string. If the flags include a positive integer n, the substitution will act on the n:th match.

Assuming you want to replace the second occurrence of substring the shop on the current line with the string it, you would therefore use

s/the shop/it/2

A snapshot from an editing session could look like the following, where the user looks at the current line with p and then decides to make the change to the second occurrence of the shop, displaying the line again after the edit (using the p flag of the s/// command):

p
He wanted to buy groceries from the shop, but preferred not having to go into the shop.
s/the shop/it/2p
He wanted to buy groceries from the shop, but preferred not having to go into it.

This feature of the s/// editing command was inherited by sed.

Kusalananda
  • 333,661