
ファイルにヘッダーを入れたいのですが、出力に最初のカンマが出てきます。コード
#!/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
デビアン: 8.5
バッシュ: 4.30
答え1
答え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
$