LoginSignup
4
3

More than 3 years have passed since last update.

【shell script】シェルスクリプトで最も簡単に文字列をsplitする方法

Posted at

シェルスクリプトで文字列を,で区切って配列を作りたい!

"wine,beer,vodka,tequila,highball"
# ↓↓↓
("wine" "beer" "vodka" "tequila" "highball")

以外と調べても出てこない…

方法

カンマをスペースに置換する→スペースで区切り配列に格納する
IFS(区切り文字)を変更するより、元々の区切り文字であるスペースに置換した方が簡単です。

alcohol="wine,beer,vodka,tequila,highball"
alcohol=(${alcohol//,/ })

説明

カンマをスペースに置換する

"wine,beer,vodka,tequila,highball"
# ↓↓↓
"wine beer vodka tequila highball"

bashの機能を使う

alcohol="wine,beer,vodka,tequila,highball"
alcohol=${alcohol//,/ }

sedを使う方法もありますが、今回は紹介しません。

スペースで区切り配列に格納する

"wine beer vodka tequila highball"
# ↓↓↓
("wine beer vodka tequila highball")

()で括る

alcohol="wine beer vodka tequila highball"
alcohol=($alcohol)

参考文献

bashの変数内文字列置換まとめ
スペース区切りの文字列を配列に格納する方法

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3