用 bash 将字符串中的字符 X 替换为字符 Y

Joo*_*zty 17 scripting bash text-processing

我正在制作bash脚本,我想用我的字符串变量中的另一个字符替换一个字符。

例子:

#!/bin/sh

string="a,b,c,d,e"
Run Code Online (Sandbox Code Playgroud)

我想替换,\n.

输出:

string="a\nb\nc\nd\ne\n"
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

hee*_*ayl 36

方法很多,这里有几个:

$ string="a,b,c,d,e"

$ echo "${string//,/$'\n'}"  ## Shell parameter expansion
a
b
c
d
e

$ tr ',' '\n' <<<"$string"  ## With "tr"
a
b
c
d
e

$ sed 's/,/\n/g' <<<"$string"  ## With "sed"
a
b
c
d
e

$ xargs -d, -n1 <<<"$string"  ## With "xargs"
a
b
c
d
e
Run Code Online (Sandbox Code Playgroud)