Ano*_*non 7 command-line bash scripts programming regex
单替换很容易:
string="Mark Shuttleworth"
echo ${string/a/o}
Mork Shuttleworth
Run Code Online (Sandbox Code Playgroud)
有可能同时做双倍吗?
echo ${string/a/o string/t/g} #doesn't work, but you get the idea
Mork Shuggleworgh
Run Code Online (Sandbox Code Playgroud)
正则表达式足以作为答案,如果可以使用它们的话。
谢谢
ste*_*ver 11
据我所知,在当前版本中做到这一点的唯一方法bash
是分两步,例如
$ string="Mark Shuttleworth"
$ string="${string//a/o}"; echo "${string//t/g}"
Mork Shuggleworgh
Run Code Online (Sandbox Code Playgroud)
尝试嵌套替换会导致错误:
$ echo "${${string//a/o}//t/g}"
bash: ${${string//a/o}//t/g}: bad substitution
Run Code Online (Sandbox Code Playgroud)
请注意,其他 shell 可能支持此类嵌套替换,例如zsh 5.2
:
~ % string="Mark Shuttleworth"
~ % echo "${${string//a/o}//t/g}"
Mork Shuggleworgh
Run Code Online (Sandbox Code Playgroud)
当然,外部工具,例如tr
,sed
,perl
可以很容易地做到这一点
$ sed 'y/at/og/' <<< "$string"
Mork Shuggleworgh
$ perl -pe 'tr /at/og/' <<< "$string"
Mork Shuggleworgh
$ tr at og <<< "$string"
Mork Shuggleworgh
Run Code Online (Sandbox Code Playgroud)
您正在替换单个字母,因此只需使用tr
:
tr at og
Run Code Online (Sandbox Code Playgroud)
这会导致每个a
被替换o
,每个t
被替换g
。以你的例子:
ek@Io:~$ tr at og <<<'Mark Shuttleworth'
Mork Shuggleworgh
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2864 次 |
最近记录: |