340
votes

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.

5
Did you want to replace any sequence of consecutive x's, y's or z's with one underscore, or did you want to replace each x, y, or z with one underscore? Also, what about mixed sequences, like AxyzB? Three underscores or one? - David Z
tr '[xyz]' will replace [ and ], too. The argument should be simply a list of characters (though ranges like a-z are okay, and in some implementations, POSIX character classes like [:digit:]). - tripleee

5 Answers

413
votes
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.

332
votes

Using Bash Parameter Expansion:

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

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.

9
votes
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

7
votes

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