Bash – Replace Character X with Character Y in a String

bashscriptingtext processing

I am making bash script and I want to replace one character with another character in my string variable.

Example:

#!/bin/sh

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

And I want to replace , with \n.

output:

string="a\nb\nc\nd\ne\n"

How can I do it?

Best Answer

So many ways, here are a few:

$ 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
Related Question