daparic
daparic

Reputation: 4444

How to replace all occurrences using sed

I couldn't make it work the way I want.

echo 'https://aaa/xx_one/bbb/xx_two/ccc' | sed 's|^\(https://.*\)xx_|\1OK_|g'
https://aaa/xx_one/bbb/OK_two/ccc

The output I wanted is: https://aaa/OK_one/bbb/OK_two/ccc

That is, I just want to replace every occurrences of xx_ with OK_ and with that specific constraint.

Need some help. I want it in sed. Thanks.

Upvotes: 0

Views: 207

Answers (1)

choroba
choroba

Reputation: 241738

If the line should start with https://, which you originally didn't say, you can use an "address" in sed:

sed '\=^https://= s/xx_/OK_/g'

Original answer: (will replace xx_ by OK_ after https://, but the line doesn't have to start with it).

Perl to the rescue:

perl -pe '1 while s=https://.*\Kxx_=OK_=g'
  • -p reads the input line by line, prints each line after processing;
  • \K in a regular expression forgets what's been matched so far. In this case, it will only replace the xx_ by OK_, but it still has to match https://.* before it;
  • The substitution runs in a while loop until there's nothing to replace.

Upvotes: 1

Related Questions