Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH printf array with field separator and newline on last entry

Tags:

bash

printf

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

like image 958
Geraint Anderson Avatar asked Oct 10 '14 16:10

Geraint Anderson


People also ask

How do you print an array element in a new line in Shell?

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 do I echo an array element in bash?

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.

How do I print an array in bash?

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.


1 Answers

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
like image 178
I-GaLaXy-I Avatar answered Sep 24 '22 07:09

I-GaLaXy-I