string 用另一个字符替换字符串中的某些字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2871181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing some characters in a string with another character
提问by Amarsh
I have a string like AxxBCyyyDEFzzLMNand I want to replace all the occurrences of x, y, and zwith _.
我有一个像AxxBCyyyDEFzzLMN这样的字符串,我想用_替换所有出现的x、y和z。
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.
我知道这echo "$string" | tr 'x' '_' | tr 'y' '_'
行得通,但我想一次性完成,而不使用管道。
回答by jkasnicki
echo "$string" | tr xyz _
would replace each occurrence of x
, y
, or z
with _
, giving A__BC___DEF__LMN
in your example.
将取代的每次出现x
,y
或z
有_
,给A__BC___DEF__LMN
你的例子。
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.
将替换重复出现的x
,y
或z
用单个_
,A_BC_DEF_LMN
在您的示例中给出。
回答by Matthew Flaschen
回答by Dylan Daniels
You might find this link helpful:
您可能会发现此链接很有帮助:
http://tldp.org/LDP/abs/html/string-manipulation.html
http://tldp.org/LDP/abs/html/string-manipulation.html
In general,
一般来说,
To replace the first match of $substring with $replacement:
用 $replacement 替换 $substring 的第一个匹配项:
${string/substring/replacement}
To replace all matches of $substring with $replacement:
用 $replacement 替换 $substring 的所有匹配项:
${string//substring/replacement}
EDIT: Note that this applies to a variable named $string.
编辑:请注意,这适用于名为 $string 的变量。
回答by Michael
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
^根据需要使用尽可能多的这些,并且您可以制作自己的 BASIC 加密
回答by Benjamin W.
Here is a solution with shell parameter expansion that replaces multiple contiguous occurrences with a single _
:
这是一个带有 shell 参数扩展的解决方案,它用单个 替换多个连续的事件_
:
$ var=AxxBCyyyDEFzzLMN
$ echo "${var//+([xyz])/_}"
A_BC_DEF_LMN
Notice that the +(pattern)
pattern requires extended pattern matching, turned on with
请注意,该模式需要扩展模式匹配,打开时使用+(pattern)
shopt -s extglob
Alternatively, with the -s
("squeeze") option of tr
:
或者,使用-s
(“挤压”)选项tr
:
$ tr -s xyz _ <<< "$var"
A_BC_DEF_LMN