anupamD
anupamD

Reputation: 952

Sed - Replace a pattern with a single character

I have the following text

I am really cool. I rate myself 10 out of 10.

Using sed I want to change the text to

I * * *. I * * 10 * * 10.

i.e (Replace [a-z] to * ) I tried to use the pattern s/[a-z]/*/g

But it replaced the text as

I ** ****** ****. I **** ****** 10 *** ** 10.

Upvotes: 0

Views: 738

Answers (2)

ndnenkov
ndnenkov

Reputation: 36101

Your pattern replaces each lower case letter with a star. You want to replace as many consecutive lower case letters with a star. Use + for repetition:

s/[a-z]\+/*/g

Upvotes: 1

N. Leavy
N. Leavy

Reputation: 1074

The answer given by @ndn is the right idea, but SED by default uses Posix 2 Basic Regular Expressions, so you don't have all of the options of full regular expressions. In particular the + operator (repeat once or more) isn't valid in SED. Fortunately the * (repeat zero or more) is. Thus we can do:

sed s/[a-z][a-z]*/*/g

Which should do what you want. You can also enable full regular expressions with a sed command line option (-r for me)

sed -r s/[a-z]+/*/g

Upvotes: 0

Related Questions