我想将标头添加到文件中,但我在输出中得到第一个逗号。代码
#!/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
答案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
$