Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a bash array on the same line

I am reading in filetype data into a bash array and need to print its contents out on the same line with spaces.

#!/bin/bash

filename=$1
declare -a myArray

readarray myArray < $1

echo "${myArray[@]}" 

I try this and even with the echo -n flag it still prints on newlines, what am I missing, would printf work better?

like image 942
Alec Beyer Avatar asked Oct 11 '16 19:10

Alec Beyer


People also ask

How do you print the elements of an array in separate lines?

To print the array elements on a separate line, we can use the printf command with the %s format specifier and newline character \n in Bash. @$ expands the each element in the array as a separate argument. %s is a format specifier for a string that adds a placeholder to the array element.

How do I print an array on the next line?

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 print a line in bash?

Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way.


1 Answers

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
like image 185
DarckBlezzer Avatar answered Sep 28 '22 02:09

DarckBlezzer