Amarsh Amarsh - 3 months ago 8
Linux Question

Bash string replacing some chars with another

I have a string like

AxxBCyyyDEFzzLMN


I want to replace all
x
and
y
and
z
with
_
so that the output is

A_BC_DEF_LMN


How to do that?

I know a series of

echo "$string" | tr 'x' '_' | tr 'y' '_'


will work, but I want to do that in one go, without using pipes

EDIT: The following worked

echo "$string" | tr '[xyz]' '_'

Answer
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.

Comments