Substituting the second occurrence of a word/phrase in ed

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. >>
Asked By: Edman

||

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.

Answered By: Kusalananda
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.