0

I want to put a header to file but I get the first comma in the output. Code

#!/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}"

Output

,1,10
masi

Expected output

1,10
masi

Debian: 8.5
Bash: 4.30

4

You left out the

bar=${bar:1}

line from the answer you linked to; you need

header=${header:1}

before your sed line to remove the leading comma.

3

Instead of using printf, why not use bash's built-in substitutions? From the section on Arrays:

   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

So you can:

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

Also you can use sed to insert a whole line, like:

$ echo masi > foo
$ IFS=, sed -i "1i${ids[*]}" foo
$ cat foo
1,10
masi
$ 
  • 3
    IFS=, echo "${ids[*]}" would pass IFS=, to the environment of echo (which wouldn't do anything with it) and would not affect the expansion of "${ids[*]}". You'd need IFS=,; echo "${ids[*]}" or even better use zsh and do echo ${(j:,:)ids} that is use an explicit operator and avoid clobbering a default setting like $IFS. – Stéphane Chazelas Nov 3 '16 at 16:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.