printf配列にこの最初のカンマがあるのはなぜですか?

printf配列にこの最初のカンマがあるのはなぜですか?

ファイルにヘッダーを追加したいが、出力に最初のカンマが表示されます。パスワード

#!/bash/bin
ids=(1 10)
filenameTarget=/tmp/result.csv
:> "${filenameTarget}"
echo "masi" > "${filenameTarget}"
header=$(printf ",%s" ${ids[@]}) # http://stackoverflow.com/a/2317171/54964
sed -i "1s/^/${header}\n/" "${filenameTarget}"

出力

,1,10
masi

期待される出力

1,10
masi

Debian: 8.5
バッシュ: 4.30

答え1

あなたは逃した

bar=${bar:1}

自分で歩くあなたがリンクした答え;あなたはする必要があります

header=${header:1}

行の前のsedコンマを削除します。

答え2

printf代わりにbashの組み込み代替機能を使用するとどうなりますか?前のセクションから始めるソート:

   subscripts  differ only when the word appears within double quotes.  If
   the word is double-quoted, ${name[*]} expands to a single word with the
   value  of each array member separated by the first character of the IFS
   special variable, and ${name[@]} expands each element of name to a sep‐
   arate  word.   When  there  are no array members, ${name[@]} expands to

したがって、次のことができます。

$ IFS=,; echo "${ids[*]}"
1,10
$

sedたとえば、次を使用して行全体を挿入することもできます。

$ echo masi > foo
$ IFS=, sed -i "1i${ids[*]}" foo
$ cat foo
1,10
masi
$ 

関連情報