이 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

데비안: 8.5
배쉬: 4.30

답변1

당신은

bar=${bar:1}

라인당신이 링크한 답변; 당신은 필요

header=${header:1}

줄 앞에 sed쉼표를 제거하십시오.

답변2

를 사용하는 대신 printfbash의 내장 대체 기능을 사용하는 것은 어떨까요? 섹션에서배열:

   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
$ 

관련 정보