Replacing some characters in a string with another character

Amarsh picture Amarsh · May 20, 2010 · Viewed 542.7k times · Source

I have a string like AxxBCyyyDEFzzLMN and I want to replace all the occurrences of x, y, and z with _.

How can I achieve this?

I know that echo "$string" | tr 'x' '_' | tr 'y' '_' would work, but I want to do that in one go, without using pipes.

Answer

jkasnicki picture jkasnicki · May 20, 2010
echo "$string" | tr xyz _

would replace each occurrence of x, y, or z with _, giving A__BC___DEF__LMN in your example.

echo "$string" | sed -r 's/[xyz]+/_/g'

would replace repeating occurrences of x, y, or z with a single _, giving A_BC_DEF_LMN in your example.