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
To print each word on a new line, we need to use the keys “%s'\n”. '%s' is to read the string till the end. At the same time, '\n' moves the words to the next line. To display the content of the array, we will not use the “#” sign.
How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.
Print Bash Array We can use the keyword 'declare' with a '-p' option to print all the elements of a Bash Array with all the indexes and details. The syntax to print the Bash Array can be defined as: declare -p ARRAY_NAME.
If you don't want to have the |
be printed, you could also remove it and just put in a space or whatever seperator you want to use (e.g. , or -):
printf '%s ' "${arr1[@]}" ; printf '\n'
If you need this more often you should use a function, due to writing the same code over and over is not the best way:
print_array ()
{
# run through array and print each entry:
local array
array=("$@")
for i in "${array[@]}" ; do
printf '%s ' "$i"
done
# print a new line
printf '\n'
}
usage:
print_array "${array_name[@]}"
example:
array01=(one two three)
print_array "${array01[@]}"
echo "this should be a new line"
output:
one two three
this should be a new line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With