109
105

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Bashの配列でjoinやsplitする

Last updated at Posted at 2013-07-31

※ここに書いた僕のコードはBashの基本ルールを確認しながら構築した手法って感じですが、コメントでは別の良いやり方が紹介されてるのでそちらも要チェックです!

※この記事の手法は、区切り文字が1文字のみが対象です。2文字以上の区切り文字でjoin/splitをしたい場合はこの記事の手法は使えないので他の方法を頑張ってください。

join

多分一番スマートと思われる方法。IFS変更の影響をサブシェルに閉じ込めて捨ててるのがポイント。

join-example.sh
arr=(a "b c" $'d\ne' f)

# join実行
str="$(IFS=,; echo "${arr[*]}")"

# 確認
echo "=== before ==="
for v in "${arr[@]}"; do
  echo "[$v]"
done
echo "=== after ==="
echo "$str"
output
=== before ===
[a]
[b c]
[d
e]
[f]
=== after ===
a,b c,d
e,f

split

splitをスマートに書くのは無理ぽいので、普通にIFSを一時退避して戻すという手順をとる。

split-example.sh
str=$'a,b c,d\ne,f'

# split実行
IFS_ORIGINAL="$IFS"
IFS=,
arr=($str)
IFS="$IFS_ORIGINAL"

# 確認
echo "=== before ==="
echo "$str"
echo "=== after ==="
for v in "${arr[@]}"; do
  echo "[$v]"
done
output
=== before ===
a,b c,d
e,f
=== after ===
[a]
[b c]
[d
e]
[f]
109
105
6

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
109
105

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?