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: Use the JavaScript replace() method You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.
Use the replace() method to replace a specific character with another.
Unlike String Class, the StringBuilder class is used to represent a mutable string of characters and has a predefined method for change a character at a specific index – setCharAt(). Replace the character at the specific index by calling this method and passing the character and the index as the parameter.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With