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]' '_'
Here is a solution with shell parameter expansion that replaces multiple contiguous occurrences with a single
_
:Notice that the
+(pattern)
pattern requires extended pattern matching, turned on withAlternatively, with the
-s
("squeeze") option oftr
:^use as many of these as you need, and you can make your own BASIC encryption
would replace each occurrence of
x
,y
, orz
with_
, givingA__BC___DEF__LMN
in your example.would replace repeating occurrences of
x
,y
, orz
with a single_
, givingA_BC_DEF_LMN
in your example.You might find this link helpful:
http://tldp.org/LDP/abs/html/string-manipulation.html
In general,
To replace the first match of $substring with $replacement:
To replace all matches of $substring with $replacement:
EDIT: Note that this applies to a variable named $string.
Using Bash Parameter Expansion: