Search code examples
bashprintf

BASH printf array with field separator and newline on last entry


How can I print out an array in BASH with a field separator between each value and a newline at the end.

The closest I can get with a single printf is printf '%s|' "${arr1[@]}" where | is the field separator. The problem with this is there is no line break at the end. Any combination of \n I try to put in there either puts in a line break on every entry or none at all!

Is there a way of doing it on one line or do I need to use printf '%s|' "${arr1[@]}";printf "\n"

Thanks,

Geraint


Solution

  • Yes, you need two commands for this. printf '%s|' "${array[@]}"; echo is perfectly conventional.

    Alternately, if you don't want the trailing |, you can temporarily modify IFS to use your chosen separator as its first character, and use "${array[*]}":

    IFS="|$IFS"; printf '%s\n' "${array[*]}"; IFS="${IFS:1}"