Replacing some characters in a string with another character

StringBash

String Problem Overview


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.

String Solutions


Solution 1 - String

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.

Solution 2 - String

Using Bash Parameter Expansion:

orig="AxxBCyyyDEFzzLMN"
mod=${orig//[xyz]/_}

Solution 3 - String

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:

${string/substring/replacement}

To replace all matches of $substring with $replacement:

${string//substring/replacement}

EDIT: Note that this applies to a variable named $string.

Solution 4 - String

Here is a solution with shell parameter expansion that replaces multiple contiguous occurrences with a single _:

$ var=AxxBCyyyDEFzzLMN
$ echo "${var//+([xyz])/_}"
A_BC_DEF_LMN

Notice that the +(pattern) pattern requires extended pattern matching, turned on with

shopt -s extglob

Alternatively, with the -s ("squeeze") option of tr:

$ tr -s xyz _ <<< "$var"
A_BC_DEF_LMN

Solution 5 - String

read filename ;
sed -i 's/letter/newletter/g' "$filename" #letter

^use as many of these as you need, and you can make your own BASIC encryption

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmarshView Question on Stackoverflow
Solution 1 - StringjkasnickiView Answer on Stackoverflow
Solution 2 - StringMatthew FlaschenView Answer on Stackoverflow
Solution 3 - StringDylan DanielsView Answer on Stackoverflow
Solution 4 - StringBenjamin W.View Answer on Stackoverflow
Solution 5 - StringMichaelView Answer on Stackoverflow