bash を使用して、文字列の文字 X を文字 Y に置き換えます。

bash を使用して、文字列の文字 X を文字 Y に置き換えます。

私は仕事をします。強く打つスクリプト、文字列変数の1文字を別の文字に置き換えたいです。

例:

#!/bin/sh

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

,に交換したいです\n

出力:

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

どうすればいいですか?

ベストアンサー1

方法はさまざまで、そのうちのいくつかを紹介します。

$ 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

おすすめ記事