22

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?

1
  • 2
    You want to replace , with literal \n or newline?
    – cuonglm
    Mar 28, 2016 at 12:19

1 Answer 1

49

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .