為什麼這個 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
$ 

相關內容