geolykos
geolykos

Reputation: 413

Sed to replace certain number of occurrences

I have the replace sed script below and it works for the first occurrence of every line but I'm trying to make it work for the first 2 occurrences per line instead of one (/1) or the whole line (/g):

sed -r '2,$s/(^ *|, *)([a-z])/\1\U\2/1' 

Is there any way to do that either by combining sed commands or creating a script?

Upvotes: 0

Views: 226

Answers (1)

Wintermute
Wintermute

Reputation: 44023

The best I can offer is

sed -r '2,$ { s/(^|,) *[a-z]/\U&/; s//\U&/; }'

The \U& trick uses the fact that the upper case version of a space is still a space; this is to make the repetition shorter. Because captures are no longer used, the regex can be simplified a little.

In the second s command, the // is a stand-in for the most recently attempted regex, so the first one is essentially executed a second time (this time matching what was originally the second appearance).

Since /1 doesn't actually do anything (replacing the first occurrence is default), I took the liberty of removing it.

Upvotes: 2

Related Questions