Replacing some characters in a string with another

2019-01-03 22:27发布

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]' '_'

5条回答
该账号已被封号
2楼-- · 2019-01-03 22:36

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
查看更多
老娘就宠你
3楼-- · 2019-01-03 22:42
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

查看更多
Evening l夕情丶
4楼-- · 2019-01-03 22:43
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.

查看更多
放荡不羁爱自由
5楼-- · 2019-01-03 22:47

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.

查看更多
爷、活的狠高调
6楼-- · 2019-01-03 23:02

Using Bash Parameter Expansion:

orig="AxxBCyyyDEFzzLMN"
mod=${orig//[xyz]/_}
查看更多
登录 后发表回答