How to print a bash array on one line

I am reading the file data into a bash array and should print its contents on the same line with spaces.

#!/bin/bash filename=$1 declare -a myArray readarray myArray < $1 echo "${myArray[@]}" 

I try to do this and even with the echo -n flag, which it still prints on new lines, what am I missing, will printf work better?

+5
source share
5 answers

readarray stores the readarray newline in each element of the array. To split them, use the -t option.

 readarray -t myArray < "$1" 
+4
source

A simple way to print in one line

 echo "${myArray[*]}" 

Example:

 myArray=( one two three four [5]=five ) echo "${myArray[*]}" #Result one two three four five 
+8
source

One of the methods:

 printf '%s\n' "${myArray[@]}" | paste -sd ' ' 

or simply:

 printf '%s ' "${myArray[*]}" 
+2
source

My favorite trick:

echo $(echo "${myArray[@]}")

+1
source

If you have array elements coming from the input, you can

  • create an array
  • add elements to it
  • then print the array in one line

script:

 #!/usr/bin/env bash declare -a array var=0 while read line do array[var]=$line var=$((var+1)) done # At this point, the user would enter text. EOF by itself ends entry. echo ${array[@]} 
0
source

Source: https://habr.com/ru/post/1258049/


All Articles