LoginSignup
0
0

More than 5 years have passed since last update.

変数・ファイルをjoinするワンライナー

Posted at

One line join function in shell script

joinってのはimplodeとか文字列結合の方のです。
joinコマンドは便利だけど、別機能ですし。

IFSいじるのは戻し忘れ怖いし、ワンラインで行きたい気持ちがあります。
複数行出力させてpaste -s -dするんですが、
読み込み元に応じた出力方式を忘れるので、その備忘録。
囲み文字 : ', デリミタ : ,でSQLのIN句パターンです。

# 配列から生成
list=(
'foo'
'bar'
'hoge hoge'
)
joined=$(printf "'%s'\n" "${list[@]}" | paste -s -d ,)

# 複数行の文字列から生成
list='
foo
bar
hoge hoge
'
joined=$(echo "$list" | sed -e '/^$/d' -e "s/.\+/'&'/" | paste -s -d ,)
joined=$(echo "$list" | awk 'NF > 0 {print "'\''"$0"'\''"}' | paste -s -d ,)

# ファイルから生成
cat list
# =>
# foo
# bar
# hoge hoge
joined=$(sed "s/.\+/'&'/g" list | paste -s -d ,)

# 結果
echo $joined
# => 'foo','bar','hoge hoge'
0
0
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
0
0