Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing some characters in a string with another character

Tags:

string

bash

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.

like image 867
Amarsh Avatar asked May 20 '10 05:05

Amarsh


People also ask

How do you replace all characters in a string with one character?

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.

What replaces one character with another?

Use the replace() method to replace a specific character with another.

How do you replace a character in a string with another character in Java?

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.


1 Answers

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.

like image 115
jkasnicki Avatar answered Sep 22 '22 10:09

jkasnicki